在MVC中添加异常增加日志

时间:2021-06-06 20:18:50

MVC的结构非常棒,基本你能想到注入的地方都可以找到地方,譬如IActionFilter,IResultFilter,IAuthorizationFilter以及IExceptionFilter

以下是测试过比较好的通用异常处理

public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext.IsChildAction)
return; if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
return; var statusCode = (int)HttpStatusCode.InternalServerError;
if (filterContext.Exception is HttpException)
{
var httpException = filterContext.Exception as HttpException;
statusCode = httpException.GetHttpCode();
}
else if (filterContext.Exception is UnauthorizedAccessException)
{
statusCode = (int)HttpStatusCode.Forbidden;
} //记录日志
_logger.Error("未捕获的异常", filterContext.Exception); if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
ReturnStatus status = new ReturnStatus
{
Status = false,
//Todo:json错误类型分类模板
ErrorMessage = filterContext.Exception.Message,
Url = "/"
};
JsonResult jsonResult = new JsonResult();
jsonResult.Data = status;
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result = jsonResult;
}
else
{
var result = CreateActionResult(filterContext, statusCode);
filterContext.Result = result;
} filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = statusCode;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}