第三节:使用Log4net和过滤器记录异常信息,返回异常给前端
上次面试,遇到,在项目中如何处理业务异常和代码异常,使用txt记录异常信息后,如何直接区分出异常的类型,异常怎么分类处理,希望大家能帮我提出宝贵的意见,完善处理异常,
统一返回参数
public class HeaderResult{ public HeaderResult() { // ReSharper disable once VirtualMemberCallInConstructor IsSucceed = false; } public virtual bool IsSucceed { get; set; } public virtual string Message { get; set; } public virtual T Result { get; set; } public virtual string StatusCode { get; set; } } </pre>
创建一个过滤器
在过滤器中拦截异常信息,使用Log4net 记录日志到txt中,获取到异常信息统一返回给前端public class ProjectExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { Exception exception = context.Exception; var exceptionType = exception.GetType().ToString(); if (exceptionType == "ProjectCore.Common.DomainException") { //用来分类处理业务逻辑 } //获取controller的名称 var controller = context.RouteData.Values["controller"].ToString(); //获取Action的名称 var action = context.RouteData.Values["Action"].ToString(); var errorPath = controller + "/" + action; LogHelper.LogError("web service error:" + errorPath, exception); //返回异常信息给前端 context.Result = new JsonResult(new HeaderResult<string> { Message = "错误路径:" + errorPath + ":错误信息" + exception.Message+"", IsSucceed = false }); //异常已处理了 context.ExceptionHandled = true; } } </pre>
public static class LogHelper { private static ILog _logger; static LogHelper() { ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository"); XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); LogHelper._logger = LogManager.GetLogger(repository.Name, "NETCorelog4net"); } public static void LogError(string msg, Exception ex) { string errorMsg = string.Format("【抛出信息】:{0} <br/>【异常类型】:{1} <br/>【异常信息】:{2} <br/>【堆栈调用】:{3}", new object[] { msg, ex.GetType().Name, ex.Message, ex.StackTrace }); errorMsg = errorMsg.Replace("\r\n", "<br>"); errorMsg = errorMsg.Replace("位置", "<strong style=\"color:red\">位置</strong>"); LogHelper._logger.Error(errorMsg); } public static void LogInfo(string msg) { LogHelper._logger.Info((object)msg); } public static void LogDebug(string msg) { LogHelper._logger.Debug((object)msg); } } </pre>
services.AddMvc(options => { options.Filters.Add(typeof(ProjectExceptionFilter)); options.Filters.Add(typeof(ModelVerificationFilter)); }). SetCompatibilityVersion(CompatibilityVersion.Version_2_1). AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰样式的key options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd"; }); </pre>