当前位置:网站首页>WebApi 打个Attribute 统一处理异常
WebApi 打个Attribute 统一处理异常
2022-08-01 00:55:00 【lee576】
我们处理异常的时候通常都要写形如以下的代码
try
{
xxxxx
}
catch(Exception ex)
{
log.write(ex.Message)
}前一段时间看杨中科的视频,其中吐糟了 mvc 的管道机制,当然用在web ui 的渲染上这个还不如做个前后端分离,因为用管道和razor视图引擎去做这些看着就很繁琐,并且很重,整个架构都复杂化了,但是作为一些AOP的处理,管道却非常的好用,下面用一个Atrribute异常过滤器来统一的处理异常,那么每次有异常出现就不用写如上的代码去手动捕获了
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;
namespace HenryMes.WebApi.App_Start
{
/// <summary>
/// 异常处理
/// </summary>
public class OnErrorResponseAttribute : ExceptionFilterAttribute
{
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public override void OnException(HttpActionExecutedContext context)
{
var error = string.IsNullOrEmpty(context.Exception.InnerException?.Message) ? context.Exception.Message : context.Exception.InnerException?.Message;
Utils.LogHelper.GetInstance().Error([email protected]"/{context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName}/{context.ActionContext.ActionDescriptor.ActionName} : {error}");
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
else if (context.Exception is TimeoutException)
{
var errorObj = new ErrowMessage() { Result = false, Message = "API调用超时" };
context.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.RequestTimeout, Content = new ObjectContent(typeof(ErrowMessage), errorObj, new JsonMediaTypeFormatter(), "application/json") };
}
//.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常,统一返回服务端错误500
else
{
var errorObj = new ErrowMessage() { Result = false, Message = error };
context.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.BadRequest, Content = new ObjectContent(typeof(ErrowMessage), errorObj, new JsonMediaTypeFormatter(), "application/json") };
}
base.OnException(context);
}
/// <summary>
///
/// </summary>
public class ErrowMessage
{
/// <summary>
///
/// </summary>
public bool Result { set; get; }
/// <summary>
///
/// </summary>
public string Message { set; get; }
}
}
}以上就是一个异常处理的过滤器,下面的Contronlller只用打上一个标签就不用再去写 try catch 了
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpPost]
[OnErrorResponse]
public IHttpActionResult Test()
{
var aaa = 999;
var b = 333;
b = 0;
var c = aaa / b;
return null;
}边栏推荐
- [Microservice] Distributed Transaction Solution - Seata
- MYSQL-批量插入数据
- Luogu P3373: Segment tree
- 类和对象:中
- Named Entity Recognition - Model: BERT-MRC
- 类和对象:上
- SVN server construction + SVN client + TeamCity integrated environment construction + VS2019 development
- Application of integrated stepper motor in UAV automatic airport
- Compose原理-视图和数据双向绑定的原理
- Likou Binary Tree
猜你喜欢
随机推荐
MYSQL事务
Inheritance and friend, static member relationship
类和对象:中
继承的注意事项
Carefully organize 16 MySQL usage specifications to reduce problems by 80% and recommend sharing with the team
值传递还是引用传递(By Value or By Reference)
Rasa 3.x Study Series - Rasa - Issues 4898 Study Notes
C# Rectangle basic usage and picture cutting
【密码学/密码分析】基于TMTO的密码分析方法
NgRx 里 first 和 take(1) 操作符的区别
[AMEX] LGBM Optuna American Express Credit Card Fraud Contest kaggle
vector的基本实现
Luogu P3373: 线段树
南方科技大学:Xiaoying Tang | AADG:视网膜图像分割领域泛化的自动增强
[Microservice] Distributed Transaction Solution - Seata
vim的基本使用-底行模式
An open source and easy-to-use flowchart drawing tool drawio
500 miles
VPGNet
二叉树遍历非递归程序 -- 使用栈模拟系统栈








