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;
        }
    }

 

相关文章

数组的定义 Dim MyArray MyArray = Array(1‚5‚123‚12‚98...
\'参数: \'code:要检测的代码 \'leixing:html或者ubb \'n...
演示效果: 代码下载: 点击下载
环境:winxp sp2 ,mysql5.0.18,mysql odbc 3.51 driver 表采...
其实说起AJAX的初级应用是非常简单的,通俗的说就是客户端(j...
<% ’判断文件名是否合法 Function isFilename(aFilename...