ASP.NET Core Web Api中间件自定义异常

编程入门 行业动态 更新时间:2024-10-24 04:44:25
本文介绍了ASP.NET Core Web Api中间件自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

ASP.NET Core Web Api中间件将自定义异常转换为基本异常

ASP.NET Core Web Api Middleware Converts Custom Exception into Base Exception

我创建了一个自定义异常类,并使用它引发异常.中间件捕获了它,但是抛出了基本异常而不是自定义异常.我不明白为什么它不能捕获自定义异常.

I have created a custom exception class and use it throw an exception. The middleware catches it but throws base exception instead of custom exception. I am not able to understand why it does not catch custom exception.

自定义例外

Custom Exception

public class CustomException : Exception { public int HttpStatusCode { get; private set; } public CustomException() { } public CustomException(int httpStatusCode, string message):base(message) { HttpStatusCode = httpStatusCode; } }

中间件

Middleware

public class ExceptionMiddleware { public readonly RequestDelegate _next; public ExceptionMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); } catch(CustomException ex) { await HandleExceptionAsync(httpContext, ex); } catch(Exception ex) { await HandleExceptionAsync(httpContext, ex); } } private static Task HandleExceptionAsync(HttpContext context, Exception ex) { int statusCode = (int)HttpStatusCode.InternalServerError; if (ex is CustomException) { CustomException se = ex as CustomException; statusCode = se.HttpStatusCode; } context.Response.ContentType = "application/json"; context.Response.StatusCode = statusCode; return context.Response.WriteAsync(JsonConvert.SerializeObject(new InternalServerErrorResponse(ex.Message))); } }

引发异常

Exception thrown

throw new CustomException(StatusCodes.Status422UnprocessableEntity, "User is already registered!");

引发异常时,中间件不会捕获自定义异常,而是基本Exception.它总是转到下面的代码块

When exception is thrown, middleware does not catch custom exception but base Exception. It always goes to the below code block

catch(Exception ex) { await HandleExceptionAsync(httpContext, ex); }

请告知.

推荐答案

您可以使用异常过滤器来处理异常并轻松操纵响应.

You can use exception filter to handle exceptions and easily manipulate response.

public class ExceptionFilter : IExceptionFilter { public ExceptionFilter(IHostingEnvironment env, ILogger<JsonExceptionFilter> logger) { _env = env; _logger = logger; } public void OnException(ExceptionContext context) { var error = new ApiResponse(); var exceptionName = context.Exception.GetType().Name; var message = context.Exception.Message; if (_env.IsDevelopment()) { error.Message = context.Exception.Message; error.Detail = context.Exception.StackTrace; } else { //Prevent To Show Exception Messages On Production error.Message = "Server Error Occured"; error.Detail = "Something wrong happened"; } context.Result = new ObjectResult(error) { //Manipulate Status Code StatusCode = 500 }; } }

并注册到Startup.cs

And register to Startup.cs

public void ConfigureServices(IServiceCollection services){ services.AddMvc(options => { //Catch the exceptions options.Filters.Add<ExceptionFilter>(); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }

更多推荐

ASP.NET Core Web Api中间件自定义异常

本文发布于:2023-11-05 09:53:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   中间件   异常   NET   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!