ASP.NET Core 内置异常中间件的四种方法

方法一

app.UseExceptionHandler(configure =>{
    configure.Run(async context => {
        var excHandler = context.Features.Get<IExceptionHandlerPathFeature>();
        var ex = excHandler.Error;
        if(ex != null)
        {
            context.Response.ContentType = "text/plain;charset=utf-8";
            await context.Response.WriteAsync(ex.ToString());
        }
    });
});

方法二

app.UseExceptionHandler(new ExceptionHandlerOptions(){
    ExceptionHandler = async context =>{
        var handler = context.Features.Get<IExceptionHandlerPathFeature>();
        var ex = handler.Error;
        if(ex != null)
        {
            context.Response.ContentType = "text/plain;charset=utf-8";
            await context.Response.WriteAsync(ex.ToString());
        }
    }
});

方法三

app.UseExceptionHandler(new ExceptionHandlerOptions{
    ExceptionHandlingPath = new PathString("/error")
});
app.Map("/error", () =>{
    return "error";
});

方法四(自定义中间件)

app.UseMiddleware<MyExceptionMiddleware>();

public class MyExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<MyExceptionMiddleware> _logger;
    public MyExceptionMiddleware(RequestDelegate next, ILogger<MyExceptionMiddleware> logger)
    {
        _logger = logger;
        _next = next;

    }
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception e)
        {
            await Handler(context,e);
        }
    }
    private async Task Handler(HttpContext context,Exception exception)
    {
        //异常处理,此处返回json类型
        context.Response.ContentType = "application/json";
        var errorResponse = new ErrorResponse
        {
            Success = false
        };
        switch (exception)
        {
            case ApplicationException ex:
                {
                    break;
                }
            case KeyNotFoundException ex:
                {
                    break;
                }
            default:
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    errorResponse.Message = exception.Message;
                    break;
                }
        }
        _logger.LogError(exception.Message);
        var resStr = JsonConvert.SerializeObject(errorResponse);
        await context.Response.WriteAsync(resStr);
    }
}
public class ErrorResponse
{
    public bool Success { get; set; } = true;
    public string Message { get; set; }
}

如果程序内部的异常被捕获掉,无论是异常中间件还是异常过滤器都不能捕获到。

posted @ 2023-12-28 12:13  leafroc  阅读(210)  评论(0编辑  收藏  举报