简体   繁体   English

为什么我的 GlobalExceptionFilter 在 NET.Core 上不起作用?

[英]Why is my GlobalExceptionFilter not working on NET.Core?

I'm trying to implement GlobalExceptionFilter in NET Core WEB API.我正在尝试在 NET Core WEB API 中实现 GlobalExceptionFilter。 This my filter code:这是我的过滤器代码:

public class GlobalExceptionFilter : IExceptionFilter, IDisposable
{
    private readonly ILogger _logger;
    public GlobalExceptionFilter(ILoggerFactory logger)
    {
        if (logger == null)
        {
            throw new ArgumentNullException(nameof(logger));
        }

        this._logger = logger.CreateLogger("Global Exception Filter");
    }

    public void Dispose()
    {
    }

    public void OnException(ExceptionContext context)
    {
        Dictionary<string, string> data = new Dictionary<string, string>();
        HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
        String message = String.Empty;

        var ex = context.Exception;

        TypeSwitch.Do(ex,
                TypeSwitch.Case<ArgumentException>(() => { statusCode = HttpStatusCode.BadRequest; }),
                TypeSwitch.Case<ArgumentNullException>(() => { statusCode = HttpStatusCode.BadRequest; }),
                TypeSwitch.Case<ArgumentOutOfRangeException>(() => { statusCode = HttpStatusCode.BadRequest; }),
                TypeSwitch.Case<KeyNotFoundException>(() => { statusCode = HttpStatusCode.NotFound; }),
                TypeSwitch.Case<DivideByZeroException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; }),
                TypeSwitch.Case<QueryFormatException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; })
            );

        HttpResponse response = context.HttpContext.Response;
        response.StatusCode = (int)statusCode;
        response.ContentType = "application/json";
        var err = new ErrorPayload()
        {
            Data = data,
            StackTrace = ex.StackTrace,
            Message = ex.Message,
            StatusCode = (int)statusCode
        };
        response.WriteAsync(JsonConvert.SerializeObject(err));
    }
}

This is my initializing code in这是我的初始化代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddMvc( config =>
        {
            config.Filters.Add(typeof(GlobalExceptionFilter));                    
        }
    );
}

And i'm testing the error handling in this controller method我正在测试这个控制器方法中的错误处理

[HttpGet("{idCliente}")]
public IActionResult GetCliente(int idCliente)
{
    throw new QueryFormatException("My Custom Exception");
}

Any ideas?有任何想法吗? thanks!谢谢!

UPDATE更新

Well, I have to admit that I asume that wasn't working because Postman shows me connection error instead of MethodNotAllowed of NotFound (404).好吧,我不得不承认我认为这不起作用,因为 Postman 向我显示连接错误而不是 NotFound (404) 的 MethodNotAllowed。 As suggested i examine the debug and the status response and was actually expected value.按照建议,我检查了调试和状态响应,实际上是预期值。

As the docs say (last section)正如文档所说(最后一部分)

Prefer middleware for exception handling.首选中间件进行异常处理。 Use exception filters only where you need to do error handling differently based on which MVC action was chosen.仅在需要根据选择的 MVC 操作进行不同错误处理的地方才使用异常过滤器。 For example, your app might have action methods for both API endpoints and for views/HTML.例如,您的应用程序可能具有用于 API 端点和视图/HTML 的操作方法。 The API endpoints could return error information as JSON, while the view-based actions could return an error page as HTML. API 端点可以以 JSON 形式返回错误信息,而基于视图的操作可以以 HTML 形式返回错误页面。

In your case, if the application only serving API:s then use the exception middleware implementation instead.在您的情况下,如果应用程序仅提供 API:s 则改用异常中间件实现。 Here's a good example of one这是一个很好的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 C# Net.Core 脚本在我的桌面上打开文件? - How to open files on my desktop using C# Net.Core script? 基于InlineData的Xunit Test / NET.Core /理论,该理论从我的模型中获取我的字段的值,同时测试控制器 - Xunit Test/NET.Core/ Theory based on InlineData that takes values of my Fields from my Model, while Testing the Controller 如何在 net.core 3.1 上使用 DI 正确配置身份核心? - How to configure properly Identity core with DI on net.core 3.1? Quazrt.net 3.0 + net.core 2.0:触发不触发 - Quazrt.net 3.0 + net.core 2.0 : trigger not fire Web API [Net.Core]上的授权失败时登录数据库 - Log to database when authorization fail on Web API [Net.Core] 如何解决 .NET.CORE 中的 Proxy Server 407 错误 - How to solve the Proxy Server 407 error in .NET.CORE 在.NET.Core上对VS代码中的一个非常简单的WebApi进行故障排除 - Troubleshooting a ridiculously simple WebApi in VS Code on NET.Core 未知构造函数的NET.Core 2.0 IOC问题 - NET.Core 2.0 IOC issue for unknown constructor 无法解决 net.core 3.0 中的依赖 HttpClient - Unable to resolve dependency HttpClient in net.core 3.0 如何在 net.core 3.1 中连接打开的 excel 应用程序? - How to connect an open excel application in net.core 3.1?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM