ExceptionMiddleware .net核心中的责任链 [英] Chain of responsibility in ExceptionMiddleware .net core
问题描述
是否可以在.net核心中间件中实现类似于责任链模式的功能,以捕获异常?因为我想全局处理异常并将其带给处理程序. 例子
is it possible to implement something similar to chain of responsibility pattern in .net core middleware which catches exceptions? Because I wanted to Handle exceptions globally and take them to their handlers. Example
try
{
}
catch(CustomException1 ex)
{
}
catch(CustomException2 ex)
{
}
...
中间件的增长非常快,以后很难维护.我想try{} catch(Exception e) { Handle(e); }
并为每个异常创建处理程序,例如NullReference等的处理程序.我想通过类型来获取异常并在指定处理程序中的handle()方法中处理该异常的解决方案.
The middleware grows really fast and it will be hard to maintain later. I wanted to try{} catch(Exception e) { Handle(e); }
and make Handlers for each Exception, for example handler for NullReference etc. I though about solution to take the exception by type and handle it in the handle() method in the specified handler.
推荐答案
我正在玩中间件,所以在启动时:
I'm toying around with middleware, so in startup:
app.UseMiddleware<ErrorHandlingMiddleware>();
中间件,我有一个通用的异常处理程序,您可以在此处添加很多(示例代码,Sentry是错误日志服务... sentry.io):
Middleware, I have one general exception handler, you could add many here (sample code, Sentry is an error log service...sentry.io):
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly IHub _sentry;
public ErrorHandlingMiddleware(RequestDelegate next, IHub sentry)
{
_sentry = sentry;
_next = next;
}
public async Task Invoke(HttpContext context/* other dependencies */)
{
try
{
await _next(context).ConfigureAwait(false);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex).ConfigureAwait(false);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
if (exception is ValueNotAcceptedException) code = HttpStatusCode.NotAcceptable;
/*if (exception is MyNotFoundException) code = HttpStatusCode.NotFound;
else if (exception is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
else if (exception is MyException) code = HttpStatusCode.BadRequest;*/
// send to Sentry.IO
_sentry.CaptureException(exception);
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
请注意,在构造函数中添加依赖项会使它成为单例,持续应用程序的生命周期(在我的情况下还可以),或者在Invoke中添加依赖项.
Note adding a dependency in the constructor will make it a singleton, last the life-cycle of the app (in my case it's fine), or else add dependency in the Invoke.
这篇关于ExceptionMiddleware .net核心中的责任链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!