与web api类似,asp.net core web mvc模板也是利用ExceptionHandler来处理错误,在starup的Configure配置数据发生时导向的/home/error
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } //处理404数据的显示信息 app.UseStatusCodePages(async context => { context.HttpContext.Response.ContentType = "text/plain"; await context.HttpContext.Response.WriteAsync($"找不到资源,状态码: {context.HttpContext.Response.StatusCode}"); }); //…… }
异常业务类定义如下
using System; namespace WebError { /// <summary> /// 产品异常 /// </summary> public class DaMeiException : ApplicationException { /// <summary> /// /// </summary> /// <param name="message"></param> public DaMeiException(string message) : base(message) { } } /// <summary> /// His项目异常 /// </summary> public class HisException : DaMeiException { /// <summary> /// /// </summary> /// <param name="message"></param> public HisException(string message) : base(message) { } } /// <summary> /// Lis项目异常 /// </summary> public class LisException : DaMeiException { /// <summary> /// /// </summary> /// <param name="message"></param> public LisException(string message) : base(message) { } } /// <summary> /// 模块异常 /// </summary> public class RegisteredException : HisException { /// <summary> /// /// </summary> /// <param name="message"></param> public RegisteredException(string message) : base(message) { } } }
Controller.cs中,因为web mvc是有view的,所以把错误返回到ErrorViewModel到View前端进行显示。同样,业务异常类DaMeiException作为错误分类处理的标志,从而完成异常的分类处理。
public IActionResult Privacy() { var ran = new Random(); switch (ran.Next(1, 4)) { case 1: int i = 0; var j = 10 / i; return Ok(); case 2: throw new RegisteredException("这是一个错误"); default: return View(); } } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { var context = HttpContext.Features.Get<IExceptionHandlerFeature>(); //如果是业务自定义异常,进行特殊处理 if (context.Error is DaMeiException) { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorMessage = context.Error.Message, ErrorType = "His" }); } else { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorMessage = context.Error.Message, ErrorType = "System" }); } }
Error.schtml 完成具体数据的展示
@model ErrorViewModel @{ ViewData["Title"] = "错误"; } <h1 class="text-danger">错误</h1> <h2 class="text-danger">一个请求处理错误</h2> @if (Model.ShowRequestId) { <h3>@Model.ErrorType</h3> <p> <strong>请求ID:</strong> <code>@Model.RequestId</code> </p> <p> @Model.ErrorMessage </p> }
每个框都有处理异常的方式,关键是要设计好业务系统中的异常关系,标准化异常处理的流程和格式,方便日志,监控系统采集汇总这些异常,为系统稳定提供保驾护航。
想要更快更方便的了解相关知识,可以关注微信公众号