异常处理

一、异常处理页

1.添加ErrorController

代码如下(示例)

  [Route("/error")]
        public IActionResult Index()
        {
            var expHanderPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            var ex = expHanderPathFeature?.Error;
            var custExp = ex as ICusKnownException;
            if (custExp == null)
            {
                var logger = HttpContext.RequestServices.GetService<ILogger<CusExceptionFilterAttribute>>();
                logger.LogError(ex, ex.Message);
                custExp = CusKnownException.UnKnownException;
            }
            else
            {
                custExp = CusKnownException.FromCusKnownException(custExp);
            }
            return View(custExp);
        }

2.添加Error视图

代码如下(示例)

@model NetCoreDemo.TestException.Exception.ICusKnownException
@{ 
    ViewData["Title"] = "Index";
}
<h1>系统发生了错误</h1>
<div>Msg:<label>@Model.Message</label></div>
<div>ErrCode:<label>@Model.ErrCode</label></div>

3.在Configure中注册异常处理

代码如下(示例)

app.UseExceptionHandler("/error");

二、自定义Filter,实现IExceptionFilter

1.添加CusExceptionFilterAttribute

代码如下(示例)

 public class CusExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            ICusKnownException cusKnownException = context.Exception as ICusKnownException;
            if (cusKnownException == null)
            {
                var logger = context.HttpContext.RequestServices.GetService<ILogger<CusExceptionFilterAttribute>>();
                logger.LogError(context.Exception, context.Exception.Message);
                cusKnownException = CusKnownException.UnKnownException;
                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            }
            else
            {
                cusKnownException = CusKnownException.FromCusKnownException(cusKnownException);
                context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
            }
            context.Result = new JsonResult(cusKnownException)
            { 
                ContentType= "application/json; charset=utf-8"
            };
        }
    }

2.在ConfigureServices中注册Filter

代码如下(示例):

 services.AddMvc(mvcOptions => {
                mvcOptions.Filters.Add<CusExceptionFilterAttribute>();
            });

三、在类上标注ExceptionFilterAttribute特性

代码如下(示例)

  [CusExceptionFilter]
    public class WeatherForecastController : ControllerBase
    {
    }

四、异常处理匿名委托方法

代码如下(示例)

  app.UseExceptionHandler(errAppBuilder => {
                errAppBuilder.Run(async context =>
                {
                    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                    ICusKnownException knownException = exceptionHandlerPathFeature.Error as ICusKnownException;
                    if (knownException == null)
                    {
                        var logger = context.RequestServices.GetService<ILogger<CusExceptionFilterAttribute>>();
                        logger.LogError(exceptionHandlerPathFeature.Error, exceptionHandlerPathFeature.Error.Message);
                        knownException = CusKnownException.UnKnownException;
                        context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    }
                    else
                    {
                        knownException = CusKnownException.FromCusKnownException(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));
                });
            });

五、源码下载

下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值