上次面試,遇到,在項目中如何處理業務異常和代碼異常,使用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; } }
在過濾器中攔截異常信息,使用Log4net 記錄日誌到txt中,獲取到異常信息統一返回給前端
web
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>
使用Log4net 記錄日誌到txt中 log4net.config網上有許多,這裏就不貼出來了
面試
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>
在Startup 下面配置
oop
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>