コード例 #1
0
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";

                    var contextFeature = context.Features.Get <IExceptionHandlerFeature>();
                    if (contextFeature != null)
                    {
                        logger.LogError($"Something went wrong: {contextFeature.Error}");

                        if (contextFeature.Error.GetType().Name.Equals("BusinessLogicException"))
                        {
                            BusinessLogicException businessLogicException = (BusinessLogicException)contextFeature.Error.GetBaseException();
                            await context.Response.WriteAsync(BaseResponse <String> .ConstructResponse(
                                                                  Status: businessLogicException.Code,
                                                                  Message: businessLogicException.ErrorMessage,
                                                                  null
                                                                  ).ToString());
                        }
                        else
                        {
                            await context.Response.WriteAsync(BaseResponse <String> .ConstructResponse(
                                                                  Status: HttpStatusCode.InternalServerError,
                                                                  Message: "Internal Server Error",
                                                                  null
                                                                  ).ToString());
                        }
                    }
                });
            });
        }
コード例 #2
0
 public Plateau CreatePlateau(Coordinate upperRightCorner)
 {
     if (upperRightCorner == null)
     {
         throw new BusinessLogicException("CreatePlateau function parameters can not be null");
     }
     if (!validationOperations.IsValidUpperRightCornerLocation(upperRightCorner))
     {
         BusinessLogicException businessLogicException = new BusinessLogicException($"Upper right corner coordinate is invalid: {upperRightCorner}");
         throw businessLogicException;
     }
     return(new Plateau(upperRightCorner));
 }
コード例 #3
0
        protected HttpException Handle(BusinessLogicException businessLogicException)
        {
            if (businessLogicException is NotFoundException)
            {
                return(ResponseHelper.Get404NotFound(businessLogicException.Message));
            }

            if (businessLogicException is ConflictException)
            {
                return(ResponseHelper.Get409Conflict(businessLogicException.Message));
            }

            return(ResponseHelper.Get500InternalServerError("Unknown business logic exception"));
        }
コード例 #4
0
        public bool IsIdleLocation(Plateau plateau, Coordinate coordinate)
        {
            if (plateau != null && plateau.Rovers != null && coordinate != null)
            {
                Rover otherRover = plateau.Rovers.Where(r => r.CurrentCoordinate.X == coordinate.X && r.CurrentCoordinate.Y == coordinate.Y).FirstOrDefault();
                if (otherRover != null)
                {
                    BusinessLogicException businessLogicException = new BusinessLogicException($"There is other rover ({otherRover.RoverCode}) on this coordinate ({coordinate.X}, {coordinate.Y}).");
                    throw businessLogicException;
                }
                return(true);
            }
            NullReferenceException nullReferenceException = new NullReferenceException("isThereAnyRover parameters: plateau, plateau.Rovers or coordinate is null");

            throw nullReferenceException;
        }
コード例 #5
0
        public bool IsValidUpperRightCornerLocation(Coordinate coordinate)
        {
            if (coordinate == null)
            {
                NullReferenceException nullReferenceException = new NullReferenceException("IsValidUpperRightCornerLocation parameters: coordinate is null");
                throw nullReferenceException;
            }
            if (coordinate.X > 0 &&
                coordinate.Y > 0)
            {
                return(true);
            }
            BusinessLogicException businessLogicException = new BusinessLogicException($"Coordinate is not valid. ({coordinate.X}, {coordinate.Y})");

            throw businessLogicException;
        }
コード例 #6
0
        public Plateau AddNewRover(Plateau plateau, Coordinate startCoordinate, Direction startDirection)
        {
            if (plateau == null || startCoordinate == null || startDirection == null)
            {
                throw new BusinessLogicException("AddNewRover function parameters can not be null");
            }
            if (!validationOperations.IsMoveAllow(plateau, startCoordinate))
            {
                BusinessLogicException businessLogicException = new BusinessLogicException($"Location is not idle. StartCoordinate: {startCoordinate}");
                throw businessLogicException;
            }
            Rover rover = new Rover(plateau, startCoordinate, startDirection);

            plateau.Rovers.Add(rover);
            plateau.SelectedRover = rover;
            return(plateau);
        }
コード例 #7
0
        public void OnException_WhenBusinessLogicException_Expects400BadRequest()
        {
            // Arrange
            var filter           = new QuizExceptionFilter();
            var ex               = new BusinessLogicException("CustomBusinessLogicException");
            var exceptionContext = this.MockExceptionContext(ex);

            // Act
            filter.OnException(exceptionContext);

            // Assert
            var result = Assert.IsType <BadRequestObjectResult>(exceptionContext.Result);

            Assert.Equal(400, result.StatusCode);
            var contract = Assert.IsType <ExceptionContract>(result.Value);

            Assert.Equal("CustomBusinessLogicException", contract.ErrorCode);
        }
コード例 #8
0
        public bool IsValidLocation(Plateau plateau, Coordinate coordinate)
        {
            if (plateau == null || coordinate == null)
            {
                NullReferenceException nullReferenceException = new NullReferenceException("isValidLocationOfPlateau parameters: plateau or coordinate is null");
                throw nullReferenceException;
            }
            if (coordinate.X >= plateau.MinX &&
                coordinate.X <= plateau.MaxX &&
                coordinate.Y >= plateau.MinX &&
                coordinate.Y <= plateau.MaxY)
            {
                return(true);
            }
            BusinessLogicException businessLogicException = new BusinessLogicException($"Coordinate is not found on the plateau.({coordinate.X}, {coordinate.Y})");

            throw businessLogicException;
        }
コード例 #9
0
        private void ShowBusinessLogicException(BusinessLogicException exception)
        {
            string header = exception.Source +
                            " - Ошибка вследситвии нарушения работы алгоритмов бизнес-логики (" + exception.HResult + ")";
            StringBuilder message = new StringBuilder();

            message.AppendLine(exception.Message);
            message.AppendLine(" ");

            if (!string.IsNullOrWhiteSpace(exception.HelpLink))
            {
                message.AppendLine("Дополнительную информацию об ошибке можно посмотреть перейдя по нижеприведенной ссылке: ");
                message.AppendLine(exception.HelpLink);
                message.AppendLine(" ");
            }

            message.AppendLine("Данная ошибка возникла в следующем методе: " + exception.TargetSite);
            message.AppendLine(exception.StackTrace);

            MessageBox.Show(message.ToString(), header, MessageBoxButton.OK, MessageBoxImage.Stop, MessageBoxResult.OK);
        }
コード例 #10
0
 protected void OnBusinessLogicException(BusinessLogicException e)
 {
     Messenger.Send(CommandName.ShowBusinessLogicException, e);
 }
コード例 #11
0
        private Dictionary <string, string> GetAllProperties(LoggingLevel level, string category, BusinessLogicException exception = null)
        {
            var properties = new Dictionary <string, string>(_properties);

            foreach (var dynamicProperty in _setDynamicProperties(level, category))
            {
                properties.Add(dynamicProperty.Key, dynamicProperty.Value);
            }
            if (exception != null)
            {
                foreach (var loggingProperty in exception.LoggingProperties)
                {
                    properties.Add(loggingProperty.Key, loggingProperty.Value?.ToString() ?? "null");
                }
            }
            return(properties);
        }
コード例 #12
0
        protected override void OnException(ExceptionContext filterContext)
        {
            //TODO: подумать о том чтобы делать параметризированный ендВорк без савечангес

            var exception = filterContext.Exception;

            Logger.Write("Message: " + exception.Message + "\r\n Data: \r\n" + exception.Data + "\r\n Trace:\r\n" + exception.StackTrace, "Exceptions", 0, 32667, TraceEventType.Error);//TODO: подкрутить вывод в лог

            #region Системные ошибки
            if (exception is SystemException)
            {
                var result = new ViewResult//TODO: Глобальная ошбика, например отключение бд, привелет к показу! Нужно редиректить на специальный лайаут, без пользовательских данных, который точно не ебнеться, и адльше смотреть, если нет коннекта к БД писать прямо об этом
                {
                    ViewName   = "Error",
                    MasterName = "",
                    ViewData   = null,
                    TempData   = filterContext.Controller.TempData
                };

                result.ViewBag.Exception     = exception;
                result.ViewBag.ExceptionText =
                    "Возникла ошибка, обратитесь к команде разработчиков через <a href='" + Url.Action("index", "feedback") + "'>форму обратной связи</a> или по <a href='mailto:[email protected]'>email</a>";

                filterContext.Result           = result;
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 500;
            }
            #endregion

            #region Ошибки приложения
            if (exception is ApplicationException)
            {
                #region Ошибки редиректа

                if (filterContext.Exception is RedirectException)
                {
                    RedirectException redirectException = (RedirectException)filterContext.Exception;

                    string url = "";

                    if (!string.IsNullOrWhiteSpace(redirectException.RedirectUrl))
                    {
                        url = redirectException.RedirectUrl;
                    }
                    else
                    {
                        url = ConstHelper.HomeUrl;
                    }


                    List <string> urlParameters = new List <string>();

                    if (!String.IsNullOrEmpty(redirectException.Message))
                    {
                        urlParameters.Add(ConstHelper.ErrorCode + "=" + ErrorService.Add(redirectException.Message));
                    }

                    if (filterContext.Exception is AuthenticationException)
                    {
                        urlParameters.Add("returnUrl" + "=" + HttpUtility.UrlEncode(HttpContext.Request.Url.ToString()));//TODO: вынести returl или внести ErrorCode
                    }
                    StringBuilder finallyUrl = new StringBuilder(url);
                    finallyUrl.Append("?");
                    for (int i = 0; i < urlParameters.Count; i++)
                    {
                        finallyUrl.Append(urlParameters[i]);

                        if (i != urlParameters.Count - 1)
                        {
                            finallyUrl.Append("&");
                        }
                    }

                    filterContext.Result           = new RedirectResult(finallyUrl.ToString());
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 500;
                    return;
                }

                if (filterContext.Exception is MvcActionRedirectException)
                {
                    MvcActionRedirectException mvcRredirectException = (MvcActionRedirectException)filterContext.Exception;
                    var result = RedirectToAction(mvcRredirectException.ActionName, mvcRredirectException.ControllerName, mvcRredirectException.RouteValues);

                    if (!String.IsNullOrEmpty(mvcRredirectException.Message))
                    {
                        result.RouteValues.Add(ConstHelper.ErrorCode, ErrorService.Add(mvcRredirectException.Message));
                    }

                    filterContext.Result           = result;
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 500;
                    return;
                }

                #endregion

                #region Ошибки ведущие на остование на этой же странице

                #region Ошибки бизнес логики
                //чтобы заюзать внутренний кеш, можно поробовать обкаст к коетроллер акстион енвокер
                if (filterContext.Exception is BusinessLogicException)
                {
                    BusinessLogicException businessLogicException = (BusinessLogicException)filterContext.Exception;

                    var                          controllerDescriptor = new ReflectedControllerDescriptor(GetType());
                    string                       actionName           = RouteData.GetRequiredString("action");
                    ActionDescriptor             actionDescriptor     = controllerDescriptor.FindAction(ControllerContext, actionName);
                    IDictionary <string, object> parameters           = GetParameterValues(ControllerContext, actionDescriptor);

                    object model = null;
                    if (parameters.Keys.Contains("model"))
                    {
                        model = parameters["model"];
                    }

                    var viewResult = new ViewResult
                    {
                        ViewName   = "",
                        MasterName = "",
                        ViewData   = new ViewDataDictionary(model),
                        TempData   = filterContext.Controller.TempData
                    };

                    viewResult.ViewBag.Exception     = businessLogicException;
                    viewResult.ViewBag.ExceptionText = String.Format(businessLogicException.Message);

                    ControllerContext context = ControllerContext;
                    try
                    {
                        viewResult.ExecuteResult(context);
                    }
                    catch//TODO: URLREFERER case
                    {
                        //if (HttpContext.Request.UrlReferrer != null)
                        //{
                        //    if(Core.UrlHelper.IsInnerUrl(HttpContext.Request.UrlReferrer.ToString()))
                        //    {
                        //    }

                        //}
                        //else
                        //{
                        var result = new ViewResult//TODO: Глобальная ошбика, например отключение бд, привелет к показу! Нужно редиректить на специальный лайаут, без пользовательских данных, который точно не ебнеться, и адльше смотреть, если нет коннекта к БД писать прямо об этом
                        {
                            ViewName   = "Error",
                            MasterName = "",
                            ViewData   = null,
                            TempData   = filterContext.Controller.TempData
                        };

                        result.ViewBag.Exception     = businessLogicException;
                        result.ViewBag.ExceptionText = String.Format(businessLogicException.Message);

                        filterContext.Result           = result;
                        filterContext.ExceptionHandled = true;
                        filterContext.HttpContext.Response.Clear();
                        filterContext.HttpContext.Response.StatusCode = 500;
                        return;
                        //}
                    }

                    filterContext.Result           = viewResult;
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 500;
                    return;
                }
                #endregion

                #region Ошибки валидации
                //чтобы заюзать внутренний кеш, можно поробовать обкаст к коетроллер акстион енвокер
                if (filterContext.Exception is ValidationException)
                {
                    ValidationException validationException = (ValidationException)filterContext.Exception;

                    var                          controllerDescriptor = new ReflectedControllerDescriptor(GetType());
                    string                       actionName           = RouteData.GetRequiredString("action");
                    ActionDescriptor             actionDescriptor     = controllerDescriptor.FindAction(ControllerContext, actionName);
                    IDictionary <string, object> parameters           = GetParameterValues(ControllerContext, actionDescriptor);

                    object model = null;
                    if (parameters.Keys.Contains("model"))
                    {
                        model = parameters["model"];
                    }

                    var viewResult = new ViewResult
                    {
                        ViewName   = "",
                        MasterName = "",
                        ViewData   = new ViewDataDictionary(model),
                        TempData   = filterContext.Controller.TempData
                    };

                    viewResult.ViewBag.ValidationException     = validationException;
                    viewResult.ViewBag.ValidationExceptionText = String.Format(validationException.Message);
                    //viewResult.ExecuteResult();
                    filterContext.Result           = viewResult;
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 500;
                    return;
                }

                #endregion

                #endregion
            }
            #endregion

            base.OnException(filterContext);
        }
コード例 #13
0
        public static IActionResult ApiErrorMessage400BadRequest(this Controller controller, BusinessLogicException businessLogicException)
        {
            var errorResponse = new ErrorResponseInfo
            {
                Error = new Error
                {
                    Code         = businessLogicException.ErrorCode.ToString(),
                    Message      = $"BusinessLogicException",
                    DebugMessage = businessLogicException.DebugMessage,
                }
            };

            return(controller.BadRequest(errorResponse));
        }
コード例 #14
0
 public void Should_not_have_message()
 {
     var exception = new BusinessLogicException();
     Assert.True(String.IsNullOrEmpty(exception.Message));
 }
コード例 #15
0
 public void Should_have_message()
 {
     var exception = new BusinessLogicException("test");
     Assert.AreEqual("test", exception.Message);
 }
コード例 #16
0
 private bool CanShowBusinessLogicException(BusinessLogicException exception)
 {
     return(exception != null);
 }