/*
         * Responsible for decorating invocation to custom exception handler.
         */
        static Node GetArgumentsToCustomHandler(IExceptionHandlerPathFeature ex, string exceptionHandlerFile)
        {
            // Creating arguments to exception handler file.
            var args = new Node("", exceptionHandlerFile);

            args.Add(new Node("message", ex.Error.Message));
            args.Add(new Node("path", ex.Path));
            args.Add(new Node("stack", ex.Error.StackTrace));
            args.Add(new Node("source", ex.Error.Source));

            /*
             * Checking if this is a Hyperlambda exception, at which point we further
             * parametrise invocation to exception file invocation with properties
             * from Hyperlambda exception class.
             */
            if (ex.Error is HyperlambdaException hypEx)
            {
                if (!string.IsNullOrEmpty(hypEx.FieldName))
                {
                    args.Add(new Node("field", hypEx.FieldName));
                }
                args.Add(new Node("status", hypEx.Status));
                args.Add(new Node("public", hypEx.IsPublic));
            }
            return(args);
        }
示例#2
0
        public ErrorResponse GetError(IExceptionHandlerPathFeature feature)
        {
            ErrorResponse errorResponse = new ErrorResponse();

            switch (feature.Error)
            {
            case InvalidOperationException exc:
                errorResponse.TitlePage  = "Corso non trovato";
                errorResponse.StatusCode = 404;
                errorResponse.ErrorView  = "CourseNotFound";
                break;

            case CourseNotFoundException exc:
                errorResponse.TitlePage  = "Corso non trovato";
                errorResponse.StatusCode = 404;
                errorResponse.ErrorView  = "CourseNotFound";
                break;

            default:
                errorResponse.TitlePage = "Errore";
                errorResponse.ErrorView = "Index";
                break;
            }
            return(errorResponse);
        }
示例#3
0
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            KraftLogger.LogCritical($"Method: public IActionResult Error for path: {exceptionHandlerPathFeature?.Path}", exceptionHandlerPathFeature?.Error);
            return(View());
        }
        /*
         * Default handler that will kick in if no "exception.hl" file is found.
         *
         * This one simply logs the exception as is, and returns the exception response accordingly.
         */
        static async Task DefaultHandler(
            IApplicationBuilder app,
            HttpContext context,
            IExceptionHandlerPathFeature ex)
        {
            var logger = app.ApplicationServices.GetService <ILogger>();

            try
            {
                await logger.ErrorAsync($"Unhandled exception occurred '{ex.Error.Message}' at '{ex.Path}'", ex.Error.StackTrace);
            }
            catch
            {
                // Silently catching to avoid new exception due to logger not being configured correctly ...
            }

            // Making sure we return exception according to specifications to caller as JSON of some sort.
            var response = GetDefaultExceptionResponse(ex, context, ex.Error.Message);

            /*
             * Notice, we have no way to determine the frontend used unless we find an explicit configuration part.
             * Hence, we've got no other options than to simply turn on everything if no frontends are declared
             * in configuration.
             */
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); //NOSONAR

            await context.Response.WriteAsync(response.ToString(Newtonsoft.Json.Formatting.Indented));
        }
示例#5
0
        public IActionResult Index()
        {
            IExceptionHandlerPathFeature feature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            ErrorViewModel error = errorService.GetError(feature.Error);

            return(View(error));
        }
示例#6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpClientFactory http, IOptionsMonitor <JupiterKeys> options)
        {
            //一wwwroot中的index.html页面作为默认页面
            FileServerOptions fileServerOptions = new FileServerOptions();

            fileServerOptions.DefaultFilesOptions.DefaultFileNames.Clear();
            fileServerOptions.DefaultFilesOptions.DefaultFileNames.Add("index.html");
            app.UseFileServer(fileServerOptions);

            app.UseExceptionHandler((x) =>
            {
                x.Run(async(context) =>
                {
                    IExceptionHandlerPathFeature exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
                    if (exceptionHandlerPathFeature?.Error is UnauthorizeException ex)
                    {
                        await context.Response.WriteAsync($"{{\"success\":False,\"message\":\"{ex.Message}\"}}");
                    }
                });
            });

            app
            .UseStatusCodePages()
            .UseStaticFiles()
            .UseCookiePolicy()
            .UseAuthentication()
            .UseCorsMiddleware()
            //.UseAutoRefreshToken(options.CurrentValue, http)
            .UseMvc();
        }
示例#7
0
        public async Task <IActionResult> GeneralException()
        {
            IExceptionHandlerPathFeature feature = HttpContext
                                                   .Features
                                                   .Get <IExceptionHandlerPathFeature>();
            ExceptionHandlerModel model = new()
            {
                DateTime                = $"{DateTime.UtcNow} (UTC)",
                OriginalPath            = feature?.Path ?? "Unknown",
                ExceptionSource         = feature?.Error.Source ?? "Unknown",
                ExceptionTargetSite     = feature?.Error.TargetSite.Name ?? "Unknown",
                ExceptionTargetHelpLink = feature?.Error.HelpLink ?? "Unknown",
                RawExceptionMessage     = feature?.Error.Message ?? "Unknown",

                StatusCode = HttpContext.Response.StatusCode.ToString() ?? "Unknown"
            };

            GoliathHelper.PrintDebugger(GoliathHelper.PrintType.Error, feature.Error.StackTrace);
            if (_signInManager.IsSignedIn(User))
            {
                await _repository.SignOutAsync();
            }
            _logger.LogError($"Encountered error in execution: {feature.Error.StackTrace}");
            TempData[TempDataKeys.Redirect]         = RedirectPurpose.Exception;
            TempData[TempDataKeys.ErrorInformation] = JsonConvert.SerializeObject(model);
            return(RedirectToActionPermanent(nameof(AuthController.Index), GoliathControllers.AuthController));
        }
        public ErrorViewData GetError(IExceptionHandlerPathFeature error)
        {
            switch (error?.Error)
            {
            case null:
                return(new ErrorViewData {
                    Title = $"Pagina {error.Path} non trovata",
                    StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError),
                    ViewReturn = "CourseNonTrovato"
                });

            case CourseNotFoundException p:
                return(new ErrorViewData {
                    Title = "Course Non Trovato",
                    StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError),
                    ViewReturn = "CourseNonTrovato"
                });

            default:
                return(new ErrorViewData {
                    Title = "Errore",
                    StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError),
                    ViewReturn = "Index"
                });
            }
        }
示例#9
0
        public void ErrorDevelopment()
        {
            IExceptionHandlerPathFeature context = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            Exception ex = context?.Error;

            HttpContext.Response.ContentType = "application/json";

            int    statusCode = Response.StatusCode;
            string message    = "Error occurred while processing your request.";

            if (ex is BusinessException businessException)
            {
                statusCode = businessException.StatusCode;
                message    = businessException.Message;
            }

            HttpContext.Response.StatusCode = statusCode;

            if (ex != null)
            {
                HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new
                {
                    context.Path,
                    ex.Message,
                    StatusCode = statusCode,
                    ex.StackTrace,
                    ex.InnerException
                }));
            }
            else
            {
                HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { message, statusCode }));
            }
        }
示例#10
0
        public void ErrorDevelopment()
        {
            IExceptionHandlerPathFeature context = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            Exception ex = context?.Error;

            ErrorResponse errorResponse = this.GetErrorFromException(ex, Response.StatusCode);

            HttpContext.Response.ContentType = "application/json";
            HttpContext.Response.StatusCode  = errorResponse.StatusCode;

            if (ex != null)
            {
                HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new
                {
                    context.Path,
                    errors = new { error = ex.Message },
                    status = errorResponse.StatusCode,
                    ex.StackTrace,
                    ex.InnerException
                }));
            }
            else
            {
                HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
            }
        }
示例#11
0
        public static void UseCustomExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(config =>
            {
                config.Run(async context =>
                {
                    context.Response.StatusCode        = StatusCodes.Status500InternalServerError;
                    context.Response.ContentType       = "application/json";
                    IExceptionHandlerPathFeature error = context.Features.Get <IExceptionHandlerPathFeature>();
                    if (error != null)
                    {
                        System.Exception ex = error.Error;
                        bool isShow         = false;

                        if (ex is CustomException)
                        {
                            isShow = true;
                        }

                        Response <NoContent> response = Response <NoContent> .Fail(
                            statusCode: StatusCodes.Status500InternalServerError,
                            isShow: isShow,
                            path: error.Path,
                            ex.Message
                            );

                        await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                    }
                });
            });
        }
示例#12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            if (!env.IsDevelopment())
            {
                ExceptionHandlerOptions exceptionHandlerOptions = new ExceptionHandlerOptions();
                exceptionHandlerOptions.ExceptionHandler = async(httpContext) =>
                {
                    await Task.Run(async() =>
                    {
                        try
                        {
                            IExceptionHandlerPathFeature exceptionPath = httpContext.Features.Get <IExceptionHandlerPathFeature>();
                            await new LogService().Log(exceptionPath.Error.ToString(), LogLevelEnum.Error);
                        }
                        catch (Exception ex)
                        {
                            _ = File.WriteAllTextAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"logs_{DateTime.Now}.txt"), ex.ToString());
                            throw;
                        }
                    });
                };
                app.UseExceptionHandler(exceptionHandlerOptions);
            }

            app.UseCors("local-angular-app");
            app.UseFileServer();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseStatusCodePagesWithReExecute("/homepage/{0}");
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });



            //app.UseSpa(spa =>
            //{
            //    // To learn more about options for serving an Angular SPA from ASP.NET Core,
            //    // see https://go.microsoft.com/fwlink/?linkid=864501

            //    spa.Options.SourcePath = "ClientApp";

            //    if (env.IsDevelopment())
            //    {
            //        spa.UseAngularCliServer(npmScript: "start");
            //    }
            //});
        }
示例#13
0
        public IActionResult Error(int?statusCode = null)
        {
            IExceptionHandlerPathFeature exceptionFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            string message = "", detail = "";

            if (statusCode.HasValue && statusCode.Value == 404)
            {
                message = "Uh oh! Looks like you’re lost...";
            }
            else if (exceptionFeature != null)
            {
                Exception exceptionThatOccurred = exceptionFeature.Error;

                message = "Looks like we're having some server issues.";
                detail  = exceptionThatOccurred.Message;

                logger.LogError(exceptionThatOccurred, exceptionThatOccurred.Message);
            }

            ViewBag.Message       = message;
            ViewBag.MessageDetail = detail;
            ViewBag.StatusCode    = statusCode ?? 500;
            return(View());
        }
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            logger.LogError(exceptionHandlerPathFeature.Error, "An exception with the following input occured: HttpContext.Request.Form: {@Form}, HttpContext.Request.Query: {@Query} at the following path: {@Path}", JsonConvert.SerializeObject(HttpContext.Request.Form), JsonConvert.SerializeObject(HttpContext.Request.Query), exceptionHandlerPathFeature.Path);
            TempData["ErrorMessage"] = "Ooops, something went wrong";
            return(RedirectToIndexActionInHomeController());
        }
示例#15
0
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionDetails = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            _logger.LogError($"The path {exceptionDetails.Path} threw an exception {exceptionDetails.Error}.");

            return(View("Error"));
        }
示例#16
0
        private IActionResult HandleError(IExceptionHandlerPathFeature feature)
        {
            var       ex = feature.Error;
            AppResult result;

            if (ex is AppValidationException validEx)
            {
                result          = validEx.Result;
                StatusCodeStyle = Resources.BadRequestMessageStyle;
                MessageTitle    = Localizer[Resources.BadRequestMessageTitle];
                Code            = (int)HttpStatusCode.BadRequest;
            }
            else if (ex is AuthorizationException authEx)
            {
                if (authEx.IsUnauthorized)
                {
                    result          = AppResult.Unauthorized(_resultLocalizer);
                    StatusCodeStyle = Resources.UnauthorizedMessageStyle;
                    MessageTitle    = Localizer[Resources.UnauthorizedMessageTitle];
                    Code            = (int)HttpStatusCode.Unauthorized;
                }
                else
                {
                    result          = AppResult.AccessDenied(_resultLocalizer);
                    StatusCodeStyle = Resources.AccessDeniedMessageStyle;
                    MessageTitle    = Localizer[Resources.AccessDeniedMessageTitle];
                    Code            = (int)HttpStatusCode.Forbidden;
                }
            }
            else if (ex is AppException appEx)
            {
                result          = appEx.Result;
                StatusCodeStyle = Resources.ErrorMessageStyle;
                MessageTitle    = Localizer[Resources.ErrorMessageTitle];
                Code            = (int)HttpStatusCode.InternalServerError;
            }
            else
            {
                if (_env.IsDevelopment())
                {
                    result = AppResult.Error(_resultLocalizer, data: ex, mess: ex.Message);
                }
                else
                {
                    result = AppResult.Error(_resultLocalizer, Localizer[Resources.ErrorMessage]);
                }

                StatusCodeStyle = Resources.ErrorMessageStyle;
                MessageTitle    = Localizer[Resources.ErrorMessageTitle];
                Code            = (int)HttpStatusCode.InternalServerError;
            }

            Message     = result.Message;
            RequestId   = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
            OriginalUrl = feature.Path;

            return(Page());
        }
        public IActionResult Index()
        {
            IExceptionHandlerPathFeature exceptionDetails = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            ViewBag.ExceptionPath    = exceptionDetails.Path;
            ViewBag.ExceptionMessage = exceptionDetails.Error.Message;

            return(PartialView("Error"));
        }
示例#18
0
 public void ErrorsLog(IExceptionHandlerPathFeature exceptionFeature)
 {
     using (SqlConnection SQLConnect =
                new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
     {
         SQLConnect.Execute("Exec Logs_Add @ErrorMessage=@E",
                            new { E = exceptionFeature.Error.Message });
     }
 }
        public IActionResult GlobalError()
        {
            IExceptionHandlerPathFeature errorInfo = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            logger.LogError("GENEL HATA YAKALAMA SISTEMI");
            logger.LogError(errorInfo.Path);
            logger.LogError(errorInfo.Error.Message);
            logger.LogError(errorInfo.Error.StackTrace);
            return(Problem("api da bir problem olustu, en kisa surede duzeltecek"));
        }
示例#20
0
        private static void SetContentTypeAndStatusCode(HttpContext context, IExceptionHandlerPathFeature contextFeature)
        {
            context.Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();
            context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;

            if (contextFeature != null && contextFeature.Error != null)
            {
                SetResponseStatusCodeForException(context, contextFeature.Error);
            }
        }
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionDetails = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            ViewBag.ExceptionPath    = exceptionDetails.Path;
            ViewBag.ExceptionMessage = exceptionDetails.Error.Message;
            ViewBag.StackTrace       = exceptionDetails.Error.StackTrace;

            return(View("Error"));
        }
        public static ErrorViewModels Create(IExceptionHandlerPathFeature exceptionDetails)
        {
            var errorViewModels = new ErrorViewModels()
            {
                ErrorMessage  = exceptionDetails.Error.Message,
                ExceptionPath = exceptionDetails.Path,
                StackTrace    = exceptionDetails.Error.StackTrace
            };

            return(errorViewModels);
        }
示例#23
0
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionHandler = this.HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            if (exceptionHandler == null)
            {
                return(this.StatusCode(404));
            }

            return(this.View());
        }
示例#24
0
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature errPath =
                HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            Exception?error = errPath?.Error;

            return(View(new ErrorViewModel {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorMessage = error?.Message ?? "Unknown Error"
            }));
        }
示例#25
0
        public IActionResult Error500()
        {
            IExceptionHandlerPathFeature exceptionFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            if (exceptionFeature != null)
            {
                ViewBag.ErrorMessage     = exceptionFeature.Error.Message;
                ViewBag.RouteOfException = exceptionFeature.Path;
            }
            return(View());
        }
示例#26
0
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            if (exceptionHandlerPathFeature?.Error is InsufficientBalanceException)
            {
                Exception exception = exceptionHandlerPathFeature?.Error;
                return(Problem(exception.StackTrace, statusCode: 400, title: exception.Message, type: nameof(InsufficientBalanceException)));
            }

            return(Problem());
        }
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature exceptionHandler =
                HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            Logger.LogError($"The path " +
                            $"{ exceptionHandler.Path } " +
                            $"threw an exception " +
                            $"{ exceptionHandler.Error }");

            return(View("Error"));
        }
示例#28
0
        /*
         * Helper method to create a JSON result from an exception, and returning
         * the result to the caller.
         */
        static JObject GetDefaultExceptionResponse(
            IExceptionHandlerPathFeature ex,
            HttpContext context,
            string msg)
        {
            // Checking if exception is a HyperlambdaException, which is handled in a custom way.
            var hypEx = ex.Error as HyperlambdaException;

            if (hypEx != null)
            {
                /*
                 * Checking if caller wants to expose exception details to client,
                 * and retrieving status code, etc from exception details.
                 */
                context.Response.StatusCode = hypEx.Status;
                if (hypEx.IsPublic)
                {
                    // Exception details is supposed to be publicly visible.
                    var response = new JObject
                    {
                        ["message"] = msg,
                    };

                    /*
                     * Checking if we've got a field name of some sort, which allows client
                     * to semantically display errors related to validators, or fields of some sort,
                     * creating more detailed feedback to the user.
                     */
                    if (!string.IsNullOrEmpty(hypEx.FieldName))
                    {
                        response["field"] = hypEx.FieldName;
                    }
                    return(response);
                }
                else
                {
                    // Exception details is not supposed to be publicly visible.
                    return(new JObject
                    {
                        ["message"] = DEFAULT_ERROR_MESSAGE
                    });
                }
            }
            else
            {
                // Default exception response, returned if exception is not Hyperlambda exception.
                return(new JObject
                {
                    ["message"] = DEFAULT_ERROR_MESSAGE
                });
            }
        }
示例#29
0
        private static async Task HandleException(HttpContext context)
        {
            IExceptionHandlerPathFeature exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
            Exception exception = exceptionHandlerPathFeature.Error;

            (ErrorApiResponse response, HttpStatusCode statusCode) = CreateErrorResponse(exception);

            string result = JsonConvert.SerializeObject(response, JsonConfig.SerializerSettings);

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)statusCode;
            await context.Response.WriteAsync(result);
        }
示例#30
0
        public ActionResult PostExceptionAsync()
        {
            IExceptionHandlerPathFeature exceptionFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            //_logger.LogWarning("THIS IS A CUSTOM MESSAGE FROM EXEPTION CONTROLLER");
            //_logger.LogError("THIS IS A CUSTOM MESSAGE FROM EXEPTION CONTROLLER");

            string message = LoggerHelper.GetMessageFromException(exceptionFeature.Error);

            _logger.LogError(exceptionFeature.Error, message);

            return(StatusCode(StatusCodes.Status500InternalServerError, message));
        }