Exemplo n.º 1
0
        private void AssertUnknownPoint(Guid pointId, BusinessException exception)
        {
            Assert.AreEqual(BLErrorCodes.NotFound, exception.ErrorCode);
            Assert.AreEqual($"Point with ID '{pointId}' not found.", exception.Message);

            _UnitOfWorkMock.Verify(u => u.Save(), Times.Never);
            _LoggerMock.VerifyLog(LogLevel.Error, Times.Once, $"Error in AppApiBL: Someone tried to access point with id '{pointId}' but it does not exsist.");
        }
Exemplo n.º 2
0
        public void TestPostUserException()
        {
            BusinessException exception = Assert.ThrowsException <BusinessException>(
                () => this.Controller.PostUser(null)
                );

            Assert.IsNotNull(exception);
        }
        public void TestCreateUserExcpetion()
        {
            BusinessException exception = Assert.ThrowsException <BusinessException>(
                () => this.Service.CreateUser(null)
                );

            Assert.IsNotNull(exception);
        }
Exemplo n.º 4
0
 private string ComposeResponse(BusinessException exception)
 {
     return(JsonConvert.SerializeObject(new
     {
         Code = exception.ErrorCode,
         exception.Message
     }));
 }
Exemplo n.º 5
0
        private void AssertUnknownUniqueId(Guid uniqueId, BusinessException exception)
        {
            Assert.AreEqual(BLErrorCodes.UserUnauthorized, exception.ErrorCode);
            Assert.AreEqual($"RegisteredID with uniqueID '{uniqueId}' is unknown", exception.Message);

            _UnitOfWorkMock.Verify(u => u.Save(), Times.Never);
            _LoggerMock.VerifyLog(LogLevel.Error, Times.Once, $"Error in AppApiBL: Someone tried to register a point but the unique id '{uniqueId}' does not exsist.");
        }
Exemplo n.º 6
0
        protected void Application_Error(object sender, EventArgs e)
        {
            string    exceptionMessage = string.Empty;
            string    exceptionType    = string.Empty;
            Exception exception        = Server.GetLastError();

            if (exception is BusinessException)
            {
                BusinessException businessException = (exception as BusinessException);
                if (new HttpRequestWrapper(Request).IsAjaxRequest())
                {
                    ClearAndsetResponse();
                    if (exception is InvalidCredentialsException || exception is AccountNotActivatedException)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }
                    else
                    {
                        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    }

                    Response.Write(JsonConvert.SerializeObject(new
                    {
                        errorcodes = businessException.ErrorCodes
                    }));
                    exceptionMessage = string.Join(",", businessException.ErrorCodes);
                    exceptionType    = "Business";
                }
            }
            else if (exception is CustomException)
            {
                ClearAndsetResponse();
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                Response.Write(JsonConvert.SerializeObject(new
                {
                    errormessage = exception.Message
                }));
                exceptionMessage = exception.Message;
                exceptionType    = "Custom";
            }
            else
            {
                if (new HttpRequestWrapper(Request).IsAjaxRequest())
                {
                    // System exceptions should not be shown to the user. show generic error message and write the exception.Message to log table.
                    ClearAndsetResponse();
                    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    Response.Write(JsonConvert.SerializeObject(new
                    {
                        errormessage = "Something went wrong while processing your request!!" //exception.Message should be written to log table
                    }));
                }
                //TODO: create a custom error page for non ajax errors.
                exceptionMessage = exception.Message;
                exceptionType    = "ServerError";
            }
            LogException(exceptionMessage, exceptionType, exception);
        }
Exemplo n.º 7
0
        private bool LoadItemIntoRow(int row, NZString ITEM_CD)
        {
            ItemValidator itemValidator = new ItemValidator();

            if (ITEM_CD != null)
            {
                BusinessException error = itemValidator.CheckItemNotExist(ITEM_CD);
                if (error != null)
                {
                    shtView.Cells[row, (int)eColView.ITEM_DESC].Value     = null;
                    shtView.Cells[row, (int)eColView.ORDER_UM_CLS].Value  = null;
                    shtView.Cells[row, (int)eColView.INV_UM_CLS].Value    = null;
                    shtView.Cells[row, (int)eColView.ORDER_UM_RATE].Value = null;
                    shtView.Cells[row, (int)eColView.INV_UM_RATE].Value   = null;
                    return(false);
                }

                ItemBIZ itemBIZ = new ItemBIZ();
                ItemDTO itemDTO = itemBIZ.LoadItem(ITEM_CD);
                shtView.Cells[row, (int)eColView.ITEM_CD].Value   = itemDTO.ITEM_CD.Value;
                shtView.Cells[row, (int)eColView.ITEM_DESC].Value = itemDTO.ITEM_DESC.Value;
                //shtView.Cells[row, (int)eColView.ORDER_UM_CLS].Value = itemDTO.ORDER_UM_CLS.Value;
                //shtView.Cells[row, (int)eColView.INV_UM_CLS].Value = itemDTO.INV_UM_CLS.Value;
                //shtView.Cells[row, (int)eColView.ORDER_UM_RATE].Value = itemDTO.ORDER_UM_RATE.Value;
                //shtView.Cells[row, (int)eColView.INV_UM_RATE].Value = itemDTO.INV_UM_RATE.Value;

                //shtView.Cells[row, (int)eColView.LOT_CONTROL_CLS].Value = itemDTO.LOT_CONTROL_CLS.Value;



                //if (itemDTO.LOT_CONTROL_CLS == DataDefine.Convert2ClassCode(DataDefine.eLOT_CONTROL_CLS.Yes))
                //{
                //    //shtView.Cells[row, (int)eColView.LOT_NO].Value = dtReceiveDate.Value.Value.ToString(DataDefine.LOT_NO_FORMAT);

                //    if (rdoReceive.Checked)
                //    {
                //        RunningNumberBIZ runningNoBiz = new RunningNumberBIZ();

                //        NZString strLotNoPrefix = runningNoBiz.GenerateLotNoPrefix(new NZDateTime(null, dtReceiveDate.Value));
                //        NZInt iLastRunningNo = runningNoBiz.GetLastLotNoRunningBox(strLotNoPrefix, new NZString(cboStoredLoc, (string)cboStoredLoc.SelectedValue), itemDTO.ITEM_CD, new NZInt(null, 0));

                //        ReceivingEntryController rcvController = new ReceivingEntryController();
                //        NZString strLotNo = rcvController.GenerateLotNo(strLotNoPrefix, ref iLastRunningNo);
                //        shtView.Cells[row, (int)eColView.LOT_NO].Value = strLotNo.StrongValue;

                //    }
                //}
                //else
                //{
                //    shtView.Cells[row, (int)eColView.LOT_NO].Value = null;
                //}

                ItemProcessDTO processDTO = itemBIZ.LoadItemProcess(ITEM_CD);
                //shtView.Cells[row, (int)eColView.LOT_SIZE].Value = processDTO.LOT_SIZE.NVL(0);
            }

            return(true);
        }
Exemplo n.º 8
0
        public void UnProcessableEntityWithMessage_Success_Should_CreateBusinessException_Detail_WithUnProcessableEntityStatusCodeAndSpecificMessage()
        {
            const string message = "Testing";
            var          ex      = BusinessException.UnProcessableEntityWithMessage(message);

            ex.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
            ex.StatusCodeNumber.Should().Be((int)HttpStatusCode.UnprocessableEntity);
            ex.Message.Should().Be(message);
        }
 public static ErrorResponse GetErrorResponse(BusinessException businessException) =>
 new ErrorResponse
 {
     Error = new ErrorInfoResponse
     {
         Code    = InvalidInputCode,
         Message = businessException.Message
     }
 };
Exemplo n.º 10
0
        public static AcceptedPlainTextActionResult Accepted(ApiController controller, string message, string exceptionCode, int deferralPeriod)
        {
            BusinessException businessException = new BusinessException();

            businessException.Message        = message;
            businessException.ExceptionCode  = exceptionCode;
            businessException.DeferralPeriod = deferralPeriod;
            return(new AcceptedPlainTextActionResult(businessException, controller.Request));
        }
Exemplo n.º 11
0
        public void NotAcceptableWithMessage_Success_Should_CreateBusinessException_Detail_WithNotAcceptableStatusCodeAndSpecificMessage()
        {
            const string message = "Testing";
            var          ex      = BusinessException.NotAcceptableWithMessage(message);

            ex.StatusCode.Should().Be(HttpStatusCode.NotAcceptable);
            ex.StatusCodeNumber.Should().Be((int)HttpStatusCode.NotAcceptable);
            ex.Message.Should().Be(message);
        }
Exemplo n.º 12
0
        public void ValidateBeforeSaveNew(SalesUnitPriceDTO dto)
        {
            BusinessException businessException = CheckSalesUnitPriceExist(dto.ITEM_CD, dto.START_EFFECTIVE_DATE, dto.CURRENCY);

            if (businessException != null)
            {
                throw businessException;
            }
        }
Exemplo n.º 13
0
        public void ThrowsWrapedExceptionWhenPostHandlingIsThrowNewExceptionAndExceptionShouldBeHandled()
        {
            var originalException = new DBConcurrencyException();

            BusinessException thrownException = ExceptionAssertHelper.Throws <BusinessException>(() =>
                                                                                                 this.exceptionManager.HandleException(originalException, "Wrap DBConcurrencyException into BusinessException, ThrowNewException postHandling"));

            Assert.AreSame(originalException, thrownException.InnerException);
        }
Exemplo n.º 14
0
        private static void RecordEvent(string msg, MediaConversionSettings settings)
        {
            Exception ex = new BusinessException(msg);

            ex.Data.Add("FFmpeg args", settings.FFmpegArgs);
            ex.Data.Add("FFmpeg output", settings.FFmpegOutput);
            ex.Data.Add("StackTrace", Environment.StackTrace);
            ErrorHandler.Error.Record(ex, settings.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
        }
        /// <summary>
        /// 异常抓获事件
        /// </summary>
        /// <param name="context">当前异常</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            object    result    = null;
            Exception exception = context.Exception;

            //把错误号转化为实际的错误信息
            string message = exception.Message;

            if (exception is Evt.Framework.Common.AuthenticationException)
            {
                //未登录
                Exception ex = exception.GetBaseException();
                result = new { status = ActionResultCode.Unauthorized, data = ex.Message };
                LogUtil.Info(GetExceptionMessage(context, ex));
            }
            else if (exception is InnerException)
            {
                //内部错误
                Exception ex = exception.GetBaseException();
                result = new { status = ActionResultCode.InnerError, data = message };
                LogUtil.Warn(GetExceptionMessage(context, ex));
            }
            else if (exception is Evt.Framework.Common.MessageException)
            {
                //数据异常
                Exception ex = exception.GetBaseException();
                result = new { status = ActionResultCode.Failed, data = message };
                LogUtil.Warn(GetExceptionMessage(context, ex));
            }
            else if (exception is BusinessException)
            {
                //业务异常
                BusinessException businessEx = exception as BusinessException;
                Exception         ex         = exception.GetBaseException();
                result = new { status = ActionResultCode.Failed, data = businessEx.Message };
                LogUtil.Warn(GetExceptionMessage(context, ex));
            }
            else if (exception is HttpRequestValidationException)
            {
                //验证异常
                Exception ex = exception.GetBaseException();
                result = new { status = ActionResultCode.Failed, data = "请输入有效字符!" };
                LogUtil.Info(GetExceptionMessage(context, ex));
            }
            else
            {
                //未知异常:全部写入Error级别的日志
                Exception ex = exception.GetBaseException();
                LogUtil.Error(GetExceptionMessage(context, ex));

                result = new { status = ActionResultCode.UnknownError, data = "出故障啦,请您稍后重新尝试!" };
            }
            context.Response = context.Request.CreateResponse();
            context.Response.Headers.Clear();
            context.Response.Content    = new StringContent(JS.Serialize(result));
            context.Response.StatusCode = System.Net.HttpStatusCode.OK;
        }
Exemplo n.º 16
0
 public static ResponseData <T> CreateErrorResponse(BusinessException ex)
 {
     return(new ResponseData <T>
     {
         Status = ResponseStates.Error.ToString(),
         MessageCode = ex.ErrorCode,
         Message = ex.Message
     });
 }
        public virtual void ShouldPerformTransaction(Transaction transaction)
        {
            var businessException = new BusinessException();

            VerifyActiveCard(businessException);

            VerifyAvailableLimit(transaction, businessException);

            VerifyTransactions(transaction, businessException);
        }
Exemplo n.º 18
0
        public static SimpleResponseDto <T> BusinessException(BusinessException be)
        {
            SimpleResponseDto <T> dto = NewInstance();

            dto.Code       = be.Code;
            dto.Message    = be.Message;
            dto.ServerTime = DateTime.Now.Ticks;

            return(dto);
        }
Exemplo n.º 19
0
        protected void TreatHandledException(BusinessException bex, BaseViewModel viewModel)
        {
            Debug.WriteLine(bex.Message);
            _logger.LogError(bex.Message);
#if DEBUG
            viewModel.ErrorMessage = string.Join(" > ", bex.FlattenInnerException());
#else
            viewModel.ErrorMessage = bex.Message;
#endif
        }
        private void ProcessBusinessException(ActionExecutedContext context,
                                              BusinessException businessException)
        {
            var error = ErrorInfoResponseFactory.GetErrorResponse(businessException);

            context.Result = new BadRequestObjectResult(error);

            context.ExceptionHandled = true;
            _logger.LogWarning(businessException, "Unhandled business exception {@ExceptionObject}", businessException);
        }
Exemplo n.º 21
0
        public void ThrowsReplacedExceptionWhenPostHandlingIsThrowNewExceptionAndExceptionShouldBeHandled()
        {
            var originalException = new DBConcurrencyException();

            BusinessException thrownException = ExceptionAssertHelper.Throws <BusinessException>(() =>
                                                                                                 this.exceptionManager.HandleException(originalException, "Replace DBConcurrencyException with BusinessException, ThrowNewException postHandling"));

            Assert.IsNotNull(thrownException);
            Assert.IsTrue(typeof(BusinessException).IsAssignableFrom(thrownException.GetType()));
        }
Exemplo n.º 22
0
        public FaultException <BusinessException> GetBusinessException()
        {
            BusinessException exception = new BusinessException("Validaciones de Negocio");

            foreach (string item in ExceptionMessages)
            {
                exception.AppMessageDetails.Add(item);
            }
            return(exception.GetFaultException());
        }
Exemplo n.º 23
0
        /// <summary>
        /// Run the FFmpeg executable with the specified command line arguments.
        /// </summary>
        private void Execute()
        {
            bool processCompletedSuccessfully = false;

            InitializeOutput();

            ProcessStartInfo info = new ProcessStartInfo(AppSetting.Instance.FFmpegPath, MediaSettings.FFmpegArgs);

            info.UseShellExecute        = false;
            info.CreateNoWindow         = true;
            info.RedirectStandardError  = true;
            info.RedirectStandardOutput = true;

            using (Process p = new Process())
            {
                try
                {
                    p.StartInfo = info;
                    // For some reason, FFmpeg sends data to the ErrorDataReceived event rather than OutputDataReceived.
                    p.ErrorDataReceived += ErrorDataReceived;
                    //p.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceived);
                    p.Start();

                    //p.BeginOutputReadLine();
                    p.BeginErrorReadLine();

                    processCompletedSuccessfully = p.WaitForExit(MediaSettings.TimeoutMs);

                    if (!processCompletedSuccessfully)
                    {
                        p.Kill();
                    }

                    p.WaitForExit();

                    if (!processCompletedSuccessfully || MediaSettings.CancellationToken.IsCancellationRequested)
                    {
                        File.Delete(MediaSettings.FilePathDestination);
                    }
                }
                catch (Exception ex)
                {
                    ErrorHandler.Error.Record(ex, MediaSettings.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
                }
            }

            if (!processCompletedSuccessfully)
            {
                Exception ex = new BusinessException(String.Format(CultureInfo.CurrentCulture, "FFmpeg timed out while processing the video or audio file. Consider increasing the timeout value. It is currently set to {0} milliseconds.", MediaSettings.TimeoutMs));
                ex.Data.Add("FFmpeg args", MediaSettings.FFmpegArgs);
                ex.Data.Add("FFmpeg output", Output);
                ex.Data.Add("StackTrace", Environment.StackTrace);
                ErrorHandler.Error.Record(ex, MediaSettings.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// main method
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine("loading map data...");

            MapConfigInfo mapConfigInfo = new MapConfigInfo();

            string lineMapStr = mapConfigInfo.GetMapConfigInfo();

            StationMap stationMap = StationMap.GetCurrentMap(lineMapStr);

            if (stationMap == null || stationMap.GetStationMap == null)
            {
                Console.WriteLine("build map error");
                Console.WriteLine("press any key to exit.");
                Console.ReadKey();
                Environment.Exit(0);
            }
            List <Station> stations = stationMap.GetStationMap;

            Console.WriteLine("1. The distance of the route A-B-C.");
            Console.WriteLine("2. The distance of the route A - D.");
            Console.WriteLine("3. The distance of the route A - D - C.");
            Console.WriteLine("4. The distance of the route A - E - B - C - D.");
            Console.WriteLine("5. The distance of the route A - E - D.");
            Console.WriteLine("6. The number of trips starting at C and ending at C with a maximum of 3 stops.In the sample data below, there are two such trips: C - D - C(2 stops).and C - E - B - C(3 stops).");
            Console.WriteLine("7. The number of trips starting at A and ending at C with exactly 4 stops.In the sample data below, there are three such trips: A to C(via B, C, D); A to C(via D, C, D); and A to C(via D, E, B).");
            Console.WriteLine("8. The length of the shortest route(in terms of distance to travel) from A to C.");
            Console.WriteLine("9. The length of the shortest route(in terms of distance to travel) from B to B.");
            Console.WriteLine("10.The number of different routes from C to C with a distance of less than 30.In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.");


            Console.WriteLine("");
            Console.WriteLine("please wait....");
            Console.WriteLine("");

            //calculate distance of the route
            Console.WriteLine($"Output #1: { BusinessException.TryRun(() => { return stationMap.Distance(new string[] { "A", "B", "C" }); })   }");
            Console.WriteLine($"Output #2: { BusinessException.TryRun(() => { return stationMap.Distance(new string[] { "A", "D" }); }) }");
            Console.WriteLine($"Output #3: { BusinessException.TryRun(() => { return stationMap.Distance(new string[] { "A", "D", "C" }); }) }");
            Console.WriteLine($"Output #4: { BusinessException.TryRun(() => { return stationMap.Distance(new string[] { "A", "E", "B", "C", "D" }); }) }");
            Console.WriteLine($"Output #5: { BusinessException.TryRun(() => { return stationMap.Distance(new string[] { "A", "E", "D" }); }) }");

            //calculate number of trips
            Console.WriteLine($"Output #6: { BusinessException.TryRun(() => { return stationMap.NumberOfTripsWithStopLimit("C", "C", 1, 3); }) }");
            Console.WriteLine($"Output #7: { BusinessException.TryRun(() => { return stationMap.NumberOfTripsWithStopLimit("A", "C", 4, 4); }) }");

            ////calculate calculate
            Console.WriteLine($"Output #8: { BusinessException.TryRun(() => { return stationMap.LengthOfShortestRoute("A", "C"); }) }");
            Console.WriteLine($"Output #9: { BusinessException.TryRun(() => { return stationMap.LengthOfShortestRoute("B", "B"); }) }");
            Console.WriteLine($"Output #10:{ BusinessException.TryRun(() => { return stationMap.NumberOfRouteWithDistanceLimit("C", "C", 30); }) }");
            Console.WriteLine("");

            Console.WriteLine("press any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 25
0
        public async Task ComparisonService_Comparison_ShouldThrow_Exception_Due_To_Null_Comparison_Value()
        {
            ComparisonService comparisonService = new ComparisonService(_comparisonRepository.Object, _applicationDbContext.Object);

            BusinessException ex = await Assert.ThrowsAsync <BusinessException>(async() => { await comparisonService.CompareAsync(new ComparisonRequestDto()
                {
                    Id = 1, ValueType = ComparisonEnum.Left
                }); });

            ex.Message.Should().Equals("No record found!");
        }
Exemplo n.º 26
0
        public void ValidateBeforeSaveNew(ItemDTO dtoItem, ItemProcessDTO dtoItemProcess)
        {
            ValidateException validateException = new ValidateException();

            //ErrorItem errorItem = null;

            #region mandatory check
            //errorItem = CheckEmptyItemCode(dtoItem.ITEM_CD);
            //if (errorItem != null)
            //    validateException.AddError(errorItem);

            //errorItem = CheckEmptyItemDesc(dtoItem.ITEM_DESC);
            //if (errorItem != null)
            //    validateException.AddError(errorItem);

            //validateException.ThrowIfHasError();

            //errorItem = CheckEmptyItemType(dtoItem.ITEM_CLS);
            //if (errorItem != null)
            //    validateException.AddError(errorItem);

            //errorItem = CheckEmptyLotControlType(dtoItem.LOT_CONTROL_CLS);
            //if (errorItem != null)
            //    validateException.AddError(errorItem);

            //errorItem = CheckEmptyStoreLoc(dtoItemProcess.STORE_LOC_CD);
            //if (errorItem != null)
            //    validateException.AddError(errorItem);

            //errorItem = CheckEmptyInventoryUM(dtoItem.INV_UM_CLS);
            //if (null != errorItem) ValidateException.ThrowErrorItem(errorItem);
            //errorItem = CheckEmptyOrderUM(dtoItem.ORDER_UM_CLS);
            //if (null != errorItem) ValidateException.ThrowErrorItem(errorItem);
            //errorItem = CheckEmptyOrderUMRate(dtoItem.ORDER_UM_RATE);
            //if (null != errorItem) ValidateException.ThrowErrorItem(errorItem);

            //errorItem = CheckEmptyUnitConvert(dtoItem.INV_UM_RATE, dtoItem.ORDER_UM_RATE);
            //if (null != errorItem) ValidateException.ThrowErrorItem(errorItem);

            //errorItem = CheckEmptyOrderProcess(dtoItemProcess.ORDER_PROCESS_CLS);
            //if (errorItem != null)
            //    validateException.AddError(errorItem);

            //errorItem = CheckEmptyConsumptionClass(dtoItemProcess.CONSUMTION_CLS);
            //if (null != errorItem) ValidateException.ThrowErrorItem(errorItem);

            BusinessException businessException = CheckItemExist(dtoItem.ITEM_CD);
            if (businessException != null)
            {
                throw businessException;
            }

            #endregion
        }
Exemplo n.º 27
0
        public static ActionResult GetError(this BusinessException exception)
        {
            var errors = new Dictionary <string, string[]>();

            errors.Add("businessError", new string[]
            {
                exception.Message
            });

            return(new BadRequestObjectResult(new ValidationProblemDetails(errors)));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ErrorViewModel_ALL"/> class.
        /// </summary>
        /// <param name="ex">
        /// The Business Exception.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Exception must not be null
        /// </exception>
        public ErrorViewModel_ALL(BusinessException ex)
        {
            if (ex == null)
            {
                throw new ArgumentNullException("ex");
            }

            this.Description = "Exception";
            this.Message     = ex.Message;
            this.Code        = ex.Code;
        }
        private static void HandleExceptionAsync(HttpContext context, BusinessException exception, HttpStatusCode code)
        {
            var serializerSettings = new JsonSerializerSettings();

            serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            var result = JsonConvert.SerializeObject(exception.Response, serializerSettings);

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            context.Response.WriteAsync(result).Wait();
        }
Exemplo n.º 30
0
 private static ErrorResponse ExtractErrorResponseFromContext(ExceptionContext context)
 {
     return(context.Exception switch
     {
         AutoMapperMappingException mappingException => mappingException.CreateErrorResponse(),
         DomainException domainException => domainException.CreateErrorResponse(),
         BusinessException businessException => businessException.CreateErrorResponse(),
         AuthorizationConfigException authorizationConfigException => authorizationConfigException.CreateErrorResponse(),
         UnauthorizedAccessException unauthorizedAccessException => unauthorizedAccessException.CreateErrorResponse(),
         _ => context.Exception.CreateErrorResponse()
     });
        public override void Arrange()
        {
            var actionGenerator =
                new DomainGenerator()
                    .With<Action<IList<Exception>>>(
                        // repetition increases likelyhood
                    l => l.Add(null),
                    l => l.Add(null),
                    l => l.Add(null),
                    l => l.Add(null),
                    l =>
                        {
                            Exception exception = new BusinessException();
                            l.Add(exception);
                            throw exception;
                        },
                    l =>
                        {
                            Exception exception = new SecurityException();
                            l.Add(exception);
                            throw exception;
                        },
                    l =>
                        {
                            Exception exception = new UnknownException();
                            l.Add(exception);
                            throw exception;
                        },
                    l =>
                        {
                            Exception exception = new AnotherUnknownException();
                            l.Add(exception);
                            throw exception;
                        });

            input =
                new DomainGenerator()
                    .With<ProcessOneWayRequestsInput>(
                        opt => opt.For(i => i.OneWayRequestsAndHandlers, new OneWayRequestsAndHandlers()))
                    .With<ProcessOneWayRequestsInput>(
                        opt => opt.For(i => i.Actions, actionGenerator.Many<Action<IList<Exception>>>(3, 3).ToList()))
                    .One<ProcessOneWayRequestsInput>();
        }
Exemplo n.º 32
0
        /// <summary>
        /// This method translates an exception from the service layer to an exception for the presentation layer
        /// </summary>
        /// <param name="faultException">The fault exception from the service layer</param>
        /// <returns>Returns the exception for the service fault</returns>            
        public WebExceptionBase GetWebExceptionFromServiceFault(System.ServiceModel.FaultException faultException)
        {
            int errorCodeInInt;
            WebExceptionBase webException = null;

            if (int.TryParse(faultException.Code.Name, out errorCodeInInt))
            {
                ExceptionErrorCode errorCode = (ExceptionErrorCode)errorCodeInInt;
                if (errorCode != ExceptionErrorCode.UnknownException)
                {
                    webException = new BusinessException(errorCode);
                }
                else
                {
                    webException = new UnknownException();
                }
            }
            else
            {
                webException = new UnknownException(faultException);
            }

            return webException;
        }
Exemplo n.º 33
0
        public void Exception_thrown_during_rollback()
        {
            // Arrange
            var sessionFactory = Substitute.For<ISessionFactory>();
            var session = Substitute.For<ISession>();
            var trans = Substitute.For<ITransaction>();

            sessionFactory.OpenSession().Returns(session);

            session.BeginTransaction(default(IsolationLevel))
                .ReturnsForAnyArgs(trans);
            session.Transaction.Returns(trans);

            trans.IsActive.Returns(true);
            trans.WasRolledBack.Returns(false);
            var exc2 = new MidCommitException();
            trans.When(x => x.Rollback()).Do(x => { throw exc2; });

            var exc1 = new BusinessException();

            // Act
            try
            {
                sessionFactory.UnitOfWork(s =>
                {
                    throw exc1;
                });

                Assert.Fail(
                    "CompoundException was not thrown, but should have been");
            }
            catch (AggregateException exc)
            {
                // Assert
                Assert.AreSame(exc1, exc.InnerExceptions[0]);
                Assert.AreSame(exc2, exc.InnerExceptions[1]);
            }
        }
 public object CreateErrorResponse(IInvocation invocation, BusinessException exception)
 {
     return CreateFailedServiceReply(invocation.GetConcreteMethodInvocationTarget().ReturnType,
                                     new ServiceFault(exception));
 }