标签:完成 常用 typeof depend exp 机制 enc write ali
public class ErrorHandlingMiddleware { private readonly RequestDelegate next; public ErrorHandlingMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context /* other dependencies */) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static Task HandleExceptionAsync(HttpContext context, Exception ex) { var code = HttpStatusCode.InternalServerError; // 500 if unexpected var Info = ""; switch (context.Response.StatusCode) { case 401: Info = "没有权限"; break; case 404: Info = "未找到服务"; break; case 403: Info = "服务器理解请求客户端的请求,但是拒绝执行此请求"; break; case 500: Info = "服务器内部错误,无法完成请求"; break; case 502: Info = "请求错误"; break; default: Info = "内部错误"; break; } LogHelp.Error(ex); var result = JsonConvert.SerializeObject(new { error = ex.Message }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return context.Response.WriteAsync(result); } }
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
Configure、中间件与ErrorHandlingMiddleware全局异常捕获
标签:完成 常用 typeof depend exp 机制 enc write ali
原文地址:https://www.cnblogs.com/hulizhong/p/10797636.html