1.使用中间件做全局异常处理,具体代码如下:
public class CustomExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<CustomExceptionMiddleware> _logger; public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception..."); await HandleExceptionAsync(httpContext, ex); } } private Task HandleExceptionAsync(HttpContext httpContext, Exception ex) { var result = JsonConvert.SerializeObject(new { isSuccess = false, message = ex.Message }); httpContext.Response.ContentType = "application/json;charset=utf-8"; return httpContext.Response.WriteAsync(result); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CustomExceptionMiddleware>(); } }
然后在Startup类的Configure方法里添加上述扩展的中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCustomExceptionMiddleware(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
2.使用过滤器做全局异常处理,具体代码如下:
public class CustomerExceptionFilter : ExceptionFilterAttribute { private readonly ILogger<CustomerExceptionFilter> _logger; public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger) { _logger = logger; } public override void OnException(ExceptionContext context) { Exception ex = context.Exception; HttpRequest request = context.HttpContext.Request; string requestUrl = $"{request.Scheme}://{request.Host.Value}{request.Path}"; string errorMsg = $"error:{ex.GetBaseException().Message};requesturl:{requestUrl}"; _logger.LogError(errorMsg); var result = new { code = 0, msg = errorMsg, data = "" }; string json = JsonConvert.SerializeObject(result); context.HttpContext.Response.StatusCode = StatusCodes.Status200OK; context.HttpContext.Response.ContentType = "application/json;charset=utf-8"; context.HttpContext.Response.WriteAsync(json); context.ExceptionHandled = true; } }