private void HandleRunQuery <TNextActionType>(Func <IQueryableRepository <TEntity>, TNextActionType> queryableRepositoryOperation, Action <TNextActionType> operationToExecuteBeforeNextOperation) { CheckForObjectAlreadyDisposedOrNot(typeof(QueryableRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(queryableRepositoryOperation.IsNotNull(), "queryableRepositoryOperation instance cannot be null"); Action operation = () => { TNextActionType queryReturnValue = _unitOfWork.IsNull() ? ExceptionHandlingUtility.HandleExceptionWithNullCheck( () => queryableRepositoryOperation(this), _exceptionHandler) : queryableRepositoryOperation(this); //TODO - proper exception handling compensating handler needs to be here if (operationToExecuteBeforeNextOperation.IsNotNull()) { operationToExecuteBeforeNextOperation(queryReturnValue); } }; if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperation(operation); } else { operation(); } }
private static PolicyBuilder BuildPolicyBuilderFromPollyTransientFailureExceptionsXMLFile() { return(ExceptionHandlingUtility.WrapFuncWithExceptionHandling(() => { PolicyBuilder policyBuilder = null; XDocument xDoc = XDocument.Load(Path.Combine(typeof(BasicPollyExceptionHandler).Assembly.Location, "ExceptionHandling", "PollyBasedExceptionHandling", "PollyTransientFailureExceptions.xml")); _pollyTransientFailureExceptions = XMLUtility.DeSerialize <PollyTransientFailureExceptions>(xDoc.ToString()); _splittedTransientFailureExceptions = _pollyTransientFailureExceptions.TransientFailureExceptions.SelectMany(x => x.CommaSeperatedTransientFailureExceptions.Split(",", StringSplitOptions.RemoveEmptyEntries)).Distinct(); if (_splittedTransientFailureExceptions.IsNotNullOrEmpty()) { string firstTransientFailureException = _splittedTransientFailureExceptions.First(); string assemblyName = _pollyTransientFailureExceptions.TransientFailureExceptions.SingleOrDefault(x => x.CommaSeperatedTransientFailureExceptions.Contains(firstTransientFailureException)).AssemblyName; Type firstTransientFailureExceptionType = MetaDataUtility.GetType(assemblyName, firstTransientFailureException); Type[] transientFailureExceptionTypesArray = new Type[1]; transientFailureExceptionTypesArray[0] = firstTransientFailureExceptionType; policyBuilder = MetaDataUtility.InvokeStaticMethod <Policy, PolicyBuilder>("Handle", transientFailureExceptionTypesArray); IEnumerable <string> transientFailureExceptionsOtherThanTheFirst = _splittedTransientFailureExceptions.Skip(1); if (transientFailureExceptionsOtherThanTheFirst.IsNotNullOrEmpty()) { transientFailureExceptionsOtherThanTheFirst.ForEach(x => { assemblyName = _pollyTransientFailureExceptions.TransientFailureExceptions.SingleOrDefault(y => y.CommaSeperatedTransientFailureExceptions.Contains(x)).AssemblyName; Type transientFailureExceptionTypeForOtherThanTheFirst = MetaDataUtility.GetType(assemblyName, x); Type[] transientFailureExceptionTypesArrayForOtherThanTheFirst = new Type[1]; transientFailureExceptionTypesArrayForOtherThanTheFirst[0] = transientFailureExceptionTypeForOtherThanTheFirst; policyBuilder = MetaDataUtility.InvokeInstanceMethod <PolicyBuilder, PolicyBuilder>(policyBuilder, "Or", transientFailureExceptionTypesArrayForOtherThanTheFirst); } ); } } return policyBuilder; }, _staticLoggerInstance)); }
public override async Task <TReturn> HandleExceptionAsync <TReturn>(Func <CancellationToken, Task <TReturn> > func, CancellationToken funcCancellationToken = default, Func <CancellationToken, Task> onExceptionCompensatingHandler = null, CancellationToken onExceptionCompensatingHandlerCancellationToken = default) { Task <TReturn> returnValue = default; try { var returnValueFromFunc = await func(funcCancellationToken); if (returnValueFromFunc is Task <TReturn> ) { returnValue = returnValueFromFunc as Task <TReturn>; } else { returnValue = Task.FromResult(returnValueFromFunc); } } catch (Exception ex) { returnValue = await ExceptionHandlingUtility.WrapFuncWithExceptionHandling(async() => { if (CheckIfExceptionsNeedsToBePollyHandled(ex)) { AsyncPolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPoliciesAsync(ex, onExceptionCompensatingHandler); return(await policyWrap.ExecuteAsync(func, funcCancellationToken) as Task <TReturn>); } return(default(Task <TReturn>)); }, _logger); await HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler, onExceptionCompensatingHandlerCancellationToken); } return(await returnValue); }
public virtual IQueryable <TEntity> Include(Expression <Func <TEntity, object> > subSelector) { CheckForObjectAlreadyDisposedOrNot(typeof(QueryableRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(subSelector.IsNotNull(), "subSelector instance cannot be null"); //TODO - proper exception handling compensating handler needs to be here return(ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => _queryable.Include(subSelector), _exceptionHandler)); }
public void CheckFatalExceptions() { Assert.IsTrue(ExceptionHandlingUtility.IsFatal(new OutOfMemoryException())); #if !SILVERLIGHT Assert.IsFalse(ExceptionHandlingUtility.IsFatal(new InsufficientMemoryException())); #endif Assert.IsTrue(ExceptionHandlingUtility.IsFatal(new TypeInitializationException("foo", new OutOfMemoryException()))); Assert.IsTrue(ExceptionHandlingUtility.IsFatal(new TargetInvocationException(new OutOfMemoryException()))); }
public override async Task DeleteAsync(TEntity item, CancellationToken token = default, Action operationToExecuteBeforeNextOperation = null) { ContractUtility.Requires <ArgumentNullException>(item.IsNotNull(), "item instance cannot be null"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperationAsync(async x => await ActualDeleteAsync(item, token == default ? x : token, operationToExecuteBeforeNextOperation).ConfigureAwait(false)); } else { //TODO - proper exception handling compensating handler needs to be here await ExceptionHandlingUtility.HandleExceptionWithNullCheck(async x => await ActualDeleteAsync(item, x, operationToExecuteBeforeNextOperation).ConfigureAwait(false), token, _exceptionHandler, null); } }
public override void Delete(TEntity item, Action operationToExecuteBeforeNextOperation = null) { ContractUtility.Requires <ArgumentNullException>(item.IsNotNull(), "item instance cannot be null"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperation(() => ActualDelete(item, operationToExecuteBeforeNextOperation)); } else { //TODO - proper exception handling compensating handler needs to be here ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => ActualDelete(item, operationToExecuteBeforeNextOperation), _exceptionHandler); } }
public override async Task DeleteAsync(TEntity item, CancellationToken token = default(CancellationToken), Action operationToExecuteBeforeNextOperation = null) { CheckForObjectAlreadyDisposedOrNot(typeof(CommandRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(item.IsNotNull(), "item instance cannot be null"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperationAsync(async x => await ActualDeleteAsync(item, token == default(CancellationToken) ? x : token, operationToExecuteBeforeNextOperation)); } else { //TODO - proper exception handling compensating handler needs to be here await ExceptionHandlingUtility.HandleExceptionWithNullCheck(async x => await ActualDeleteAsync(item, x, operationToExecuteBeforeNextOperation), token, _exceptionHandler, null); } }
public override void Delete(IEnumerable <TEntity> items, Action operationToExecuteBeforeNextOperation = null) { ContractUtility.Requires <ArgumentNullException>(items.IsNotNull(), "items instance cannot be null"); ContractUtility.Requires <ArgumentOutOfRangeException>(items.IsNotEmpty(), "items count should be greater than 0"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperation(() => ActualDelete(items, operationToExecuteBeforeNextOperation)); } else { //TODO - proper exception handling compensating handler needs to be here ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => ActualDelete(items, operationToExecuteBeforeNextOperation), _exceptionHandler); } }
public override void Update(TEntity item, Action operationToExecuteBeforeNextOperation = null) { CheckForObjectAlreadyDisposedOrNot(typeof(CommandRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(item.IsNotNull(), "item instance cannot be null"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperation(() => ActualUpdate(item, operationToExecuteBeforeNextOperation)); } else { //TODO - proper exception handling compensating handler needs to be here ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => ActualUpdate(item, operationToExecuteBeforeNextOperation), _exceptionHandler); } }
public override async Task UpdateAsync(IEnumerable <TEntity> items, CancellationToken token = default, Action operationToExecuteBeforeNextOperation = null) { ContractUtility.Requires <ArgumentNullException>(items.IsNotNull(), "items instance cannot be null"); ContractUtility.Requires <ArgumentOutOfRangeException>(items.IsNotEmpty(), "items count should be greater than 0"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperationAsync(async x => await ActualUpdateAsync(items, token == default ? x : token, operationToExecuteBeforeNextOperation).ConfigureAwait(false)); } else { //TODO - proper exception handling compensating handler needs to be here await ExceptionHandlingUtility.HandleExceptionWithNullCheck(async x => await ActualUpdateAsync(items, x, operationToExecuteBeforeNextOperation).ConfigureAwait(false), token, _exceptionHandler, null); } }
public override async Task BulkInsertAsync(IEnumerable <TEntity> items, CancellationToken token = default(CancellationToken), Action operationToExecuteBeforeNextOperation = null) { CheckForObjectAlreadyDisposedOrNot(typeof(CommandRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(items.IsNotNull(), "items instance cannot be null"); ContractUtility.Requires <ArgumentOutOfRangeException>(items.IsNotEmpty(), "items count should be greater than 0"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperationAsync(async x => await ActualBulkInsertAsync(items, token == default(CancellationToken) ? x : token, operationToExecuteBeforeNextOperation)); } else { //TODO - proper exception handling compensating handler needs to be here await ExceptionHandlingUtility.HandleExceptionWithNullCheck(async x => await ActualBulkInsertAsync(items, x, operationToExecuteBeforeNextOperation), token, _exceptionHandler, null); } }
public override void BulkUpdate(IEnumerable <TEntity> items, Action operationToExecuteBeforeNextOperation = null) { CheckForObjectAlreadyDisposedOrNot(typeof(CommandRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(items.IsNotNull(), "items instance cannot be null"); ContractUtility.Requires <ArgumentOutOfRangeException>(items.IsNotEmpty(), "items count should be greater than 0"); if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperation(() => ActualBulkUpdate(items, operationToExecuteBeforeNextOperation)); } else { //TODO - proper exception handling compensating handler needs to be here ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => ActualBulkUpdate(items, operationToExecuteBeforeNextOperation), _exceptionHandler); } }
/// <summary> /// This method can run synchronous as well as asynchronous operations within a transaction /// in the order in which the operations are written in the consumer class.Here synchronous /// as well as asynchronous operations are hadnled since "Task" also inherently handles both /// synchronous and asynchronous scenarios. /// /// </summary> /// <param name="shouldCommitSynchronousOperationsFirst"></param> /// <param name="shouldAutomaticallyRollBackOnTransactionException"></param> /// <param name="shouldThrowOnException"></param> /// <returns></returns> public async Task CommitAsync(CancellationToken token = default(CancellationToken), bool shouldAutomaticallyRollBackOnTransactionException = true, bool shouldThrowOnException = true) { CheckForObjectAlreadyDisposedOrNot(typeof(UnitOfWork).FullName); ContractUtility.Requires <ArgumentOutOfRangeException>(_operationsQueue.Count > 0, "Atleast one operation must be there to be executed."); ContractUtility.Requires <NotSupportedException>(_operationsQueue.Any(x => x.AsyncOperation.IsNotNull()), "If CommitAsync method is used,there needs to be atleast one async operation exceuted." + "Please use Commit method(instead of CommitAsync) if there is not " + "a single async operation."); await ExceptionHandlingUtility.HandleExceptionWithNullCheck(async x => { _scope = TransactionUtility.GetTransactionScope(_isoLevel, _scopeOption, true); try { while (_operationsQueue.Count > 0) { #if TEST ThrowExceptionForRollbackCheck(); #endif OperationData operationData = _operationsQueue.Dequeue(); if (operationData.Operation.IsNotNull()) { operationData.Operation(); } else if (operationData.AsyncOperation.IsNotNull()) { await operationData.AsyncOperation(x); } } CompleteScope(() => { _scope.Complete(); // this just completes the transaction.Not yet committed here. _scope.Dispose(); // After everthing runs successfully within the transaction // and after completion, this should be called to actually commit the data // within the transaction scope. }, shouldAutomaticallyRollBackOnTransactionException, shouldThrowOnException); } catch (Exception ex) { //Although ex is not exactly a commit exception but still passing it to reuse Rollback method.Using the Rollback //method to reuse exception handling and dispose the transaction scope object(else it can cause issues for the //future transactions). Rollback(ex); } }, token, _exceptionHandler, null);//TODO - proper exception handling compensating handler needs to be here }
public override void HandleException(Action action, Action onExceptionCompensatingHandler = null) { try { action(); } catch (Exception ex) { ExceptionHandlingUtility.WrapActionWithExceptionHandling(() => { if (_splittedTransientFailureExceptions.IsNotNullOrEmpty() && _splittedTransientFailureExceptions.Contains(ex.GetType().Name) && _policies.IsNotNullOrEmpty()) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPolicies(ex, onExceptionCompensatingHandler); policyWrap.Execute(action); } }, _logger); HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler); } }
public override async Task HandleExceptionAsync(Func <CancellationToken, Task> action, CancellationToken actionCancellationToken = default(CancellationToken), Func <CancellationToken, Task> onExceptionCompensatingHandler = null, CancellationToken onExceptionCompensatingHandlerCancellationToken = default(CancellationToken)) { try { await action(actionCancellationToken); } catch (Exception ex) { ExceptionHandlingUtility.WrapActionWithExceptionHandling(async() => { if (CheckIfExceptionsNeedsToBePollyHandled(ex)) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPoliciesAsync(ex, onExceptionCompensatingHandler); await policyWrap.ExecuteAsync(action, actionCancellationToken); } }, _logger); await HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler, onExceptionCompensatingHandlerCancellationToken); } }
public override void HandleException(Action action, Action onExceptionCompensatingHandler = null) { try { action(); } catch (Exception ex) { ExceptionHandlingUtility.WrapActionWithExceptionHandling(() => { if (CheckIfExceptionsNeedsToBePollyHandled(ex)) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPolicies(ex, onExceptionCompensatingHandler); policyWrap.Execute(action); } }, _logger); HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler); } }
public override async Task HandleExceptionAsync(Func <CancellationToken, Task> action, CancellationToken actionCancellationToken = default(CancellationToken), Func <CancellationToken, Task> onExceptionCompensatingHandler = null, CancellationToken onExceptionCompensatingHandlerCancellationToken = default(CancellationToken)) { try { await action(actionCancellationToken); } catch (Exception ex) { ExceptionHandlingUtility.WrapActionWithExceptionHandling(async() => { if (_splittedTransientFailureExceptions.IsNotNullOrEmpty() && _splittedTransientFailureExceptions.Contains(ex.GetType().Name) && _policies.IsNotNullOrEmpty()) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPoliciesAsync(ex, onExceptionCompensatingHandler); await policyWrap.ExecuteAsync(action, actionCancellationToken); } }, _logger); await HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler, onExceptionCompensatingHandlerCancellationToken); } }
/// <summary> /// Cancels the operation. /// </summary> /// <remarks> /// Upon completion of the operation, check the IsCanceled property to determine whether /// or not the operation was successfully canceled. Note that successful cancellation /// does not guarantee state changes were prevented from happening on the server. /// </remarks> /// <exception cref="NotSupportedException"> is thrown when <see cref="SupportsCancellation"/> /// is <c>false</c>. /// </exception> public void Cancel() { if (!this.SupportsCancellation) { throw new NotSupportedException(Resources.AsyncOperation_CancelNotSupported); } this.EnsureNotCompleted(); if (this._cancellationTokenSource != null) { try { this._cancellationTokenSource?.Cancel(); } catch (AggregateException ex) { throw ExceptionHandlingUtility.GetUnwrappedException(ex);; } } }
/// <summary> /// Comits all the data within this unit of work instance in an atomic way i.e. all or none get transacted. /// Order of operations of different instances of same type or different types needs to be handled at /// the Business or Service Layer. /// </summary> /// <param name="shouldAutomaticallyRollBackOnTransactionException">when set to true(default value) /// the RollBack method need not be called from the consumer class</param> public void Commit(bool shouldAutomaticallyRollBackOnTransactionException = true, bool shouldThrowOnException = true) { ContractUtility.Requires <ArgumentOutOfRangeException>(_operationsQueue.IsNotNullOrEmpty(), "Atleast one operation must be there to be executed."); ContractUtility.Requires <NotSupportedException>(_operationsQueue.All(x => x.AsyncOperation.IsNull()), "Async operations are not supported by Commit method.Use CommitAsync instead."); ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => { _scope = TransactionUtility.GetTransactionScope(_isoLevel, _scopeOption); try { while (_operationsQueue.Count > 0) { #if TEST ThrowExceptionForRollbackCheck(); #endif OperationData operationData = _operationsQueue.Dequeue(); if (operationData.Operation.IsNotNull()) { operationData.Operation(); } } CompleteScope(() => { _scope.Complete(); // this just completes the transaction.Not yet committed here. _scope.Dispose(); // After everthing runs successfully within the transaction // and after completion, this should be called to actually commit the data // within the transaction scope. }, shouldAutomaticallyRollBackOnTransactionException, shouldThrowOnException); } catch (Exception ex) { //Although ex is not exactly a commit exception but still passing it to reuse Rollback method.Using the Rollback //method to reuse exception handling and dispose the transaction scope object(else it can cause issues for the //future transactions). Rollback(ex); } }, _exceptionHandler);//TODO - proper exception handling compensating handler needs to be here }
/// <summary> /// For Exception handling scenario, refer - /// http://stackoverflow.com/questions/9780908/using-unity-interception-to-solve-exception-handling-as-a-crosscutting-concern /// </summary> /// <param name="input"></param> /// <param name="getNext"></param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { return(ExceptionHandlingUtility.HandleExceptionWithNullCheck(() => { ExecuteBeforeMethodInvocation(input); IMethodReturn methodReturn = getNext().Invoke(input, getNext); Exception methodReturnException = methodReturn.Exception; if (methodReturnException.IsNotNull()) { if (_exceptionHandler.IsNull()) { _logger.LogException(methodReturnException); } throw methodReturnException; } else { ExecuteAfterMethodInvocation(input, methodReturn); } return methodReturn; }, _exceptionHandler)); }
public override TReturn HandleException <TReturn>(Func <TReturn> action, Action onExceptionCompensatingHandler = null) { TReturn returnValue = default(TReturn); try { returnValue = action(); } catch (Exception ex) { returnValue = ExceptionHandlingUtility.WrapFuncWithExceptionHandling(() => { if (CheckIfExceptionsNeedsToBePollyHandled(ex)) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPolicies(ex, onExceptionCompensatingHandler); return(policyWrap.Execute(action)); } return(default(TReturn)); }, _logger); HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler); } return(returnValue); }
public override TReturn HandleException <TReturn>(Func <TReturn> action, Action onExceptionCompensatingHandler = null) { TReturn returnValue = default(TReturn); try { returnValue = action(); } catch (Exception ex) { returnValue = ExceptionHandlingUtility.WrapFuncWithExceptionHandling(() => { if (_splittedTransientFailureExceptions.IsNotNullOrEmpty() && _splittedTransientFailureExceptions.Contains(ex.GetType().Name) && _policies.IsNotNullOrEmpty()) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPolicies(ex, onExceptionCompensatingHandler); return(policyWrap.Execute(action)); } return(default(TReturn)); }, _logger); HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler); } return(returnValue); }
public override async Task <TReturn> HandleExceptionAsync <TReturn>(Func <CancellationToken, Task <TReturn> > func, CancellationToken funcCancellationToken = default(CancellationToken), Func <CancellationToken, Task> onExceptionCompensatingHandler = null, CancellationToken onExceptionCompensatingHandlerCancellationToken = default(CancellationToken)) { Task <TReturn> returnValue = default(Task <TReturn>); try { returnValue = await func(funcCancellationToken) as Task <TReturn>; } catch (Exception ex) { returnValue = await ExceptionHandlingUtility.WrapFuncWithExceptionHandling(async() => { if (_splittedTransientFailureExceptions.IsNotNullOrEmpty() && _splittedTransientFailureExceptions.Contains(ex.GetType().Name) && _policies.IsNotNullOrEmpty()) { PolicyWrap policyWrap = GetPolicyWrapWithProperFallbackActionSetForFallbackPoliciesAsync(ex, onExceptionCompensatingHandler); return(await policyWrap.ExecuteAsync(func, funcCancellationToken) as Task <TReturn>); } return(default(Task <TReturn>)); }, _logger); await HandleExceptionWithThrowCondition(ex, onExceptionCompensatingHandler, onExceptionCompensatingHandlerCancellationToken); } return(await returnValue); }
/// <summary> /// Transforms the specified exception as appropriate into a fault message that can be sent /// back to the client. /// </summary> /// <remarks> /// This method will also trace the exception if tracing is enabled. /// </remarks> /// <param name="e">The exception that was caught.</param> /// <returns>The exception to return.</returns> internal static FaultException <DomainServiceFault> CreateFaultException(Exception e) { Debug.Assert(!e.IsFatal(), "Fatal exception passed in"); DomainServiceFault fault = new DomainServiceFault(); HttpContext context = HttpContext.Current; // Unwrap any TargetInvocationExceptions to get the real exception. e = ExceptionHandlingUtility.GetUnwrappedException(e); // we always send back a 200 (i.e. not re-throwing) with the actual error code in // the results (except fo 404) because silverlight only supports 404/500 error code. If customErrors // are disabled, we'll also send the error message. int errorCode = (int)HttpStatusCode.InternalServerError; if (e is InvalidOperationException) { // invalid operation exception at root level generates BadRequest errorCode = (int)HttpStatusCode.BadRequest; } else if (e is UnauthorizedAccessException) { errorCode = (int)HttpStatusCode.Unauthorized; } else { DomainException dpe = e as DomainException; if (dpe != null) { // we always propagate error info to the client for DomainServiceExceptions fault.ErrorCode = dpe.ErrorCode; fault.ErrorMessage = FormatExceptionMessage(dpe); fault.IsDomainException = true; if (context != null && context.IsCustomErrorEnabled == false) { // also send the stack trace if custom errors is disabled fault.StackTrace = dpe.StackTrace; } return(new FaultException <DomainServiceFault>(fault, new FaultReason(new FaultReasonText(fault.ErrorMessage ?? String.Empty, CultureInfo.CurrentCulture)))); } else { HttpException httpException = e as HttpException; if (httpException != null) { errorCode = httpException.GetHttpCode(); if (errorCode == (int)HttpStatusCode.NotFound) { // for NotFound errors, we don't provide detailed error // info, we just rethrow throw e; } } } } // set error code. Also set error message if custom errors is disabled fault.ErrorCode = errorCode; if (context != null && !context.IsCustomErrorEnabled) { fault.ErrorMessage = FormatExceptionMessage(e); fault.StackTrace = e.StackTrace; } return(new FaultException <DomainServiceFault>(fault, new FaultReason(new FaultReasonText(fault.ErrorMessage ?? String.Empty, CultureInfo.CurrentCulture)))); }