ASP.NET Core Web API异常处理 [英] ASP.NET Core Web API exception handling

查看:1624
本文介绍了ASP.NET Core Web API异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用常规ASP.NET Web API多年后,我开始使用ASP.NET Core作为我的新REST API项目。我没有看到在ASP.NET Core Web API中处理异常的好办法。我试图实现异常处理过滤器/属性:

I started using ASP.NET Core for my new REST API project after using regular ASP.NET Web API for many years. I don't see a good way to handle exceptions in ASP.NET Core Web API. I tried to implement exception handling filter/attribute:

public class ErrorHandlingFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        HandleExceptionAsync(context);
        context.ExceptionHandled = true;
    }

    private static void HandleExceptionAsync(ExceptionContext context)
    {
        var exception = context.Exception;

        if (exception is MyNotFoundException)
            SetExceptionResult(context, exception, HttpStatusCode.NotFound);
        else if (exception is MyUnauthorizedException)
            SetExceptionResult(context, exception, HttpStatusCode.Unauthorized);
        else if (exception is MyException)
            SetExceptionResult(context, exception, HttpStatusCode.BadRequest);
        else
            SetExceptionResult(context, exception, HttpStatusCode.InternalServerError);
    }

    private static void SetExceptionResult(
        ExceptionContext context, 
        Exception exception, 
        HttpStatusCode code)
    {
        context.Result = new JsonResult(new ApiResponse(exception))
        {
            StatusCode = (int)code
        };
    }
}

这里是我的启动过滤器注册:

And here is my Startup filter registration:

services.AddMvc(options =>
{
    options.Filters.Add(new AuthorizationFilter());
    options.Filters.Add(new ErrorHandlingFilter());
});

我遇到的问题是当我的 AuthorizationFilter 它不被 ErrorHandlingFilter 处理。我期望它被抓到那里,就像它与旧的ASP.NET Web API一样。

The issue I was having is that when exception occurred in my AuthorizationFilter it's not being handled by ErrorHandlingFilter. I was expecting it to be caught there just like it worked with old ASP.NET Web API.

那么如何捕捉所有应用程序异常以及Action Filters的任何异常?

So how can I catch all application exceptions as well as any exceptions from Action Filters?

推荐答案

异常处理中间件



经过不同的异常处理方法的许多实验后,我终于使用了中间件。它为我的ASP.NET Core Web API应用程序工作最好。它处理应用程序异常以及过滤器的异常。这是我的异常处理中间件:

Exception Handling Middleware

After many experiments with different exception handling approaches I ended up using middleware. It worked the best for my ASP.NET Core Web API application. It handles application exceptions as well as exceptions from filters. Here is my exception handling middleware:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;

    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context /* other scoped dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        if      (exception is MyNotFoundException)     code = HttpStatusCode.NotFound;
        else if (exception is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
        else if (exception is MyException)             code = HttpStatusCode.BadRequest;

        var result = JsonConvert.SerializeObject(new { error = exception.Message });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}

在MVC之前注册 启动类:

Register it before MVC in Startup class:

app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseMvc();

以下是异常响应的示例:

Here is an example of exception response:

{ "error": "Authentication token is not valid." }

您可以添加堆栈跟踪,异常类型名称,错误代码或任何您想要的。非常灵活希望这是您的良好起点!

You can add stack trace, exception type name, error codes or anything you want to it. Very flexible. Hope it's a good starting point for you!

这篇关于ASP.NET Core Web API异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆