AOP的最主要原因
- C#中的try catch丑的一比
- 省了很多代码
- 符合restful api的规范
不多bb,直接开搞
定义一个异常拦截的类 要继承一下这个boy
public class ErrorFilter : IExceptionFilter
{
//全局错误拦截
public void OnException(ExceptionContext context)
{
//单独拦截自定义错误
context.HttpContext.Response.StatusCode =
context.Exception switch
{
ArgumentException => StatusCodes.Status422UnprocessableEntity,
WeixinMiniProgramExcption => StatusCodes.Status422UnprocessableEntity,
NuonuoException => StatusCodes.Status422UnprocessableEntity,
//...
_ => throw context.Exception //其他的异常直接抛出去,视为服务器端异常
};
//上面是C#9中switch的新用法,非常的好用
var problem = new ProblemDetails()
{
Detail = context.Exception.Message,
Status = context.HttpContext.Response.StatusCode,
Title = "An error has occurred!",
Instance = context.HttpContext.Request.Path,
};
//自定义的扩展
problem.Extensions.Add("traceId", context.HttpContext.TraceIdentifier);
context.Result = new JsonResult(problem);
}
}
老规矩,依赖注入一下
public void ConfigureServices(IServiceCollection services)
{
//在添加控制器的时候配置一下
//这个东西好像在net fw时代就有了
//算了,不要掉头发就好
// ^ ^
services.AddControllers(mvc =>
{
mvc.Filters.Add(new ErrorFilter());
});
}
前端接收的错误示例
{
"title": "An error has occurred!",
"status": 422,
"detail": "这是个ArgumentException! (Parameter 'value')",
"instance": "/api/deliveries",
"traceId": "8001cb37-3f00-c900-b63f-84710c7967bb",
}