本文旨在:
1 继承ExceptionFilterAttribute,重写Override OnException(ExceptionContext context)处理异常
2 使用.netCore的依赖注入,在属性中注入日志框架,记录异常日志
以下详细回答以上两个问题:
1 继承ExceptionFilterAttribute,重写Override OnException(ExceptionContext context)处理异常
新建class文件,命名ExceptionHandler,继承特性ExceptionFilterAttribute,重写 OnException,处理异常 重新赋值请求页面返回的Result,返回json,string content,Error Page三种形式
public class ExceptionHandle : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { var ex = context.Exception; var controllername = context.RouteData.Values["controller"].ToString(); var actionname = context.RouteData.Values["action"].ToString(); if (context.ExceptionHandled == false) { context.Result= ReturnResult(resultType.ContentResult,ex); } context.ExceptionHandled = true; //异常已处理了 } }
处理异常返回的Result:共三种形式 Page,Json,html content
private IActionResult ReturnResult(resultType rtype, Exception ex) { IActionResult result; switch (rtype) { case resultType.ContentResult: result = new ContentResult { Content = ex.Message, StatusCode = StatusCodes.Status500InternalServerError, ContentType = "text/html;charset=utf-8" }; break; case resultType.JsonResult: result = new JsonResult(new { msg = ex.Message }); break; case resultType.Redirect: result = new RedirectToRouteResult( new RouteValueDictionary{ { "controller","Home"}, {"action","Error" }, {"msg",ex.Message } } ); break; default: result = new RedirectResult("../home/error"); break; } return result; } enum resultType { ContentResult = 1, JsonResult = 2, Redirect = 3 }
2 使用.netCore的依赖注入,在属性中注入日志框架,记录异常日志
startup.cs 依赖注入容器:
public void ConfigureServices(IServiceCollection services) { ... services.AddScoped<ExceptionHandle>(); }
构造函数注入参数 logger
public class ExceptionHandle : ExceptionFilterAttribute { private readonly ILogger<ExceptionHandle> _logger; public ExceptionHandle(ILogger<ExceptionHandle> logger) { _logger = logger; } public override void OnException(ExceptionContext context) { _logger.LogError(ex.Message, context.Exception);//调用 } }
Action调用:ServiceFilter
[ServiceFilter(typeof(ExceptionHandle))] public IActionResult Index(DateTime dt, long sjc) { var chushu = 0; var i = 1 / chushu; return View() }
总结:定义继承自ExceptionFilterAttribute属性类的Filter文件类,重写OnException方法,如果不需要在属性类中做写日志,则删掉构造函数,自然也不需要在startup.cs文件中做依赖注入,用法也不需要使用
[ServiceFilter(typeof(ExceptionHandle))] 使用最传统的[ExceptionHandle]即可
//[ServiceFilter(typeof(ExceptionHandle))] [ExceptionHandle]
public IActionResult Index(DateTime dt, long sjc) { var chushu = 0; var i = 1 / chushu; return View() }