ASP.NET Core--全局异常处理
作者:互联网
使用过滤器做全局异常处理,具体代码如下:
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; } }
标签:Core,ASP,--,errorMsg,request,public,context,logger,HttpContext 来源: https://www.cnblogs.com/hobelee/p/16368494.html