原文链接: https://www.cnblogs.com/ysmc/p/16512669.html
以下代码自定义简单的异常处理中间件Demo
ExceptionMiddleWare
1 public class ExceptionMiddleWare 2 { 3 private readonly RequestDelegate _next; 4 public ExceptionMiddleWare(RequestDelegate next) 5 { 6 _next = next; 7 } 8 public async Task Invoke(HttpContext context) 9 { 10 try 11 { 12 await _next.Invoke(context); 13 } 14 catch (Exception ex) 15 { 16 await HandleExceptionAsync(context, ex); 17 } 18 } 19 private async Task HandleExceptionAsync(HttpContext context, Exception exception) 20 { 21 var time = DateTime.Now.ToString("yyyyMMddhhmmss"); 22 FileHelper.WriteInformationFile(exception.ToString(), Path.Combine("Errlog", DateTime.Now.ToString("yyyyMMdd"), time + ".txt")); 23 var response = context.Response; 24 response.ContentType = "application/json"; 25 response.StatusCode = (int)HttpStatusCode.InternalServerError; 26 await response.WriteAsync(JsonConvert.SerializeObject(new 27 { 28 // customize as you need 29 error = new 30 { 31 message = "系统错误,请联系管理员", 32 errfile = time 33 } 34 })); 35 } 36 }
ExceptionMiddleWareBuilder
public static class ExceptionMiddleWareBuilder { public static IApplicationBuilder ExceptionMiddleWare(this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionMiddleWare>(); }
Startup
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.HttpRequestMiddleWare(); if (env.IsDevelopment()) { //app.UseDeveloperExceptionPage(); app.ExceptionMiddleWare(); } else app.ExceptionMiddleWare(); app.UseMvc(); }