public IActionResult Index()
        {
            // 获取当前上下文里面报出的异常信息
            var exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            var ex = exceptionHandlerPathFeature?.Error;

            // 特殊处理,尝试转换为 IKnownException
            var knownException = ex as IKnownException;

            // 对于未知异常,我们并不应该把错误异常完整地输出给客户端,而是应该定义一个特殊的信息 Unknown 传递给用户
            // Unknown 其实也是一个 IKnownException 的实现,它的 Message = "未知错误", ErrorCode = 9999
            // 也就是说我们在控制器 throw new Exception("报个错"); 就会看到错误信息
            if (knownException == null)
            {
                var logger = HttpContext.RequestServices.GetService <ILogger <MyExceptionFilterAttribute> >();
                // 我们看到的信息是未知错误,但是在我们的日志系统里面,我们还是记录的原有的异常信息
                logger.LogError(ex, ex.Message);
                knownException = KnownException.Unknown;
            }
            else// 当识别到异常是已知的业务异常时,输出已知的异常,包括异常消息,错误状态码和错误信息,就是在 IKnownException 中的定义
            {
                knownException = KnownException.FromKnownException(knownException);
            }
            return(View(knownException));
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //1 开发人员异常页 显示请求异常的详细信息。置于要捕获其异常的任何中间件前面
                //该页包括关于异常和请求的以下信息:
                //堆栈跟踪
                //查询字符串参数(如果有)
                //Cookie(如果有)
                //标头
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //2 异常处理程序页
                //为生产环境配置自定义错误处理页,请使用异常处理中间件。
                //中间件
                //捕获并记录异常。
                //在备用管道中为指定的页或控制器重新执行请求。 如果响应已启动,则不会重新执行请求。
                app.UseExceptionHandler("/error");
                app.UseHsts();
            }

            app.UseExceptionHandler(errApp =>
            {
                errApp.Run(async context =>
                {
                    //3 访问异常lambda
                    //使用 IExceptionHandlerPathFeature 访问错误处理程序控制器或页中的异常和原始请求路径:
                    var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
                    IKnownException knownException  = exceptionHandlerPathFeature.Error as IKnownException;
                    if (knownException == null)
                    {
                        var logger = context.RequestServices.GetService <ILogger <MyExceptionFilterAttribute> >();
                        logger.LogError(exceptionHandlerPathFeature.Error, exceptionHandlerPathFeature.Error.Message);
                        knownException = KnownException.Unknown;
                        context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    }
                    else
                    {
                        knownException = KnownException.FromKnownException(knownException);
                        context.Response.StatusCode = StatusCodes.Status200OK;
                    }
                    var jsonOptions = context.RequestServices.GetService <IOptions <JsonOptions> >();
                    context.Response.ContentType = "application/json; charset=utf-8";
                    await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(knownException, jsonOptions.Value.JsonSerializerOptions));
                });
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        /// <summary>
        /// 异常处理页
        /// </summary>
        /// <returns></returns>
        //[Route("{id}")]
        public IActionResult Index(int id)
        {
            var exception     = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            var ex            = exception?.Error;
            var knowException = ex as IKnownException;

            if (knowException == null)
            {
                var logger = HttpContext.RequestServices.GetService <ILogger <MyExceptionFilterAttribute> >();
                logger.LogError(ex, ex.Message);
                knowException = KnownException.Unknown;
            }
            else
            {
                knowException = KnownException.FromKnownException(knowException);
            }
            return(View(knowException));
        }
Esempio n. 4
0
        public IActionResult Index()
        {
            var feature        = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            var err            = feature?.Error;
            var knownException = err as IKnownException;

            if (knownException == null)
            {
                //var logger = HttpContext.RequestServices.GetService<ILogger<ErrorController>>();
                _logger.LogError(err, err.Message);
                knownException = KnownException.UnKnown;
            }
            else
            {
                knownException = KnownException.FromKnownException(knownException);
            }
            return(View(knownException));
        }
Esempio n. 5
0
        public IActionResult Error1()
        {
            var exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            var ex             = exceptionHandlerPathFeature?.Error;
            var knownException = ex as IknownException;

            if (knownException == null)
            {
                var logger = HttpContext.RequestServices.GetService <ILogger <HomeController> >();
                logger.LogError(ex, ex.Message);
                knownException = KnownException.Unknown;
            }
            else
            {
                knownException = KnownException.FromKnownException(knownException);
            }

            return(View(knownException));
        }
Esempio n. 6
0
        public void OnException(ExceptionContext context)
        {
            var knowException = context.Exception as IKnownException;

            context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
            if (knowException == null)
            {
                // 紀錄log
                _logger.LogError(context.Exception.ToString());
                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                ;
                knowException = KnownException.UnKnow();
            }

            context.Result = new JsonResult(KnownException.FromKnownException(knowException))
            {
                ContentType = "application/json;charset=utf-8"
            };
        }
Esempio n. 7
0
        public IActionResult Index()
        {
            var exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            var ex = exceptionHandlerPathFeature?.Error;

            var knownException = ex as IKnownException;

            if (knownException == null)
            {
                Console.WriteLine(ex + ex.Message);
                knownException = KnownException.Unknown;
            }
            else
            {
                knownException = KnownException.FromKnownException(knownException);
            }
            return(View(knownException));
        }
Esempio n. 8
0
        public void OnException(ExceptionContext context)
        {
            var ex             = context.Exception;
            var knownException = ex as IKnownException;

            if (knownException == null)
            {
                //var logger = context.HttpContext.RequestServices.GetService<ILogger<MyExceptionFilter>>();
                _logger.LogError(ex, ex.Message);
                knownException = KnownException.UnKnown;
                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            }
            else
            {
                knownException = KnownException.FromKnownException(knownException);
                context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
            }

            context.Result = new JsonResult(knownException)
            {
                ContentType = "application/json charset=utf-8"
            };
        }
Esempio n. 9
0
        private async Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
        {
            // 在 Features 里面获取异常
            //var exceptionHandlerPathFeature = httpContext.Features.Get<IExceptionHandlerPathFeature>();

            // 1.识别异常是否为业务异常(IKnownException)
            IKnownException knownException = ex as IKnownException;

            // 2.为空系统异常,否则业务异常
            if (knownException == null)
            {
                knownException = KnownException.UnKnown;
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            }
            else
            {
                knownException = KnownException.FromKnownException(knownException);
                httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }

            // 3.把响应信息通过json 的方式输出出去
            httpContext.Response.ContentType = "application/json; charset=utf-8";
            await httpContext.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(knownException));
        }