当前位置:网站首页>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;
}
边栏推荐
- Carefully organize 16 MySQL usage specifications to reduce problems by 80% and recommend sharing with the team
- /etc/resolv.conf的作用
- MYSQL查询截取优化分析
- ROS2系列知识(4): 理解【服务】的概念
- 二叉树遍历非递归程序 -- 使用栈模拟系统栈
- Keil nRF52832下载失败
- Rainbow share | how to use moving targets defense technology to guard against the unknown
- 500 miles
- Interview Question: Implementing Deadlocks
- Kyoto University: Masaki Waga | Dynamic Masking for Reinforcement Learning in Black Box Environments
猜你喜欢
pycaret源码分析:下载数据集\Lib\site-packages\pycaret\datasets.py
C# Rectangle basic usage and picture cutting
TFC CTF 2022 WEB Diamand WriteUp
南方科技大学:Xiaoying Tang | AADG:视网膜图像分割领域泛化的自动增强
MYSQL二阶段提交
Cmake introductory study notes
推荐系统:常用评价指标总结【准确率、精确率、召回率、命中率、(归一化折损累计增益)NDCG、平均倒数排名(MRR)、ROC曲线、AUC(ROC曲线下的面积)、P-R曲线、A/B测试】
Southern University of Science and Technology: Xiaoying Tang | AADG: Automatic Enhancement for Generalization in the Field of Retinal Image Segmentation
Team of Professor Chen Jianyu of Tsinghua University | Contact Safety Reinforcement Learning Framework Based on Contact-rich Robot Operation
WeChat applet page syntax
随机推荐
RTL8762DK 点灯/LED(三)
/usr/sbin/vmware-authdlauncher: error while loading shared libraries: libssl.so.1.0.2*解决办法
JS时间戳的意义是什么?知道sql会考虑加时间戳,JS的时间戳用于什么场景?
Matlab/ArcGIS processing GPM global monthly precipitation data
thymeleaf iterates the map collection
vim的基本使用-命令模式
Southern University of Science and Technology: Xiaoying Tang | AADG: Automatic Enhancement for Generalization in the Field of Retinal Image Segmentation
欧拉系统(euleros):升级Mysql
What is the meaning of JS timestamp?Know SQL will consider to add a timestamp, JS timestamp for the scene?
网关gateway跨域
Named Entity Recognition - Model: BERT-MRC
Compose原理-视图和数据双向绑定的原理
qlib量化源码分析:qlib/qlib/contrib/model/gbdt.py
MVCC总结
The difference between /usr/local/bin and /usr/bin
微信小程序之小程序页面语法
LeetCode--打家劫舍问题
ECCV2022 Workshop | 复杂环境中的多目标跟踪和分割
精心总结十三条建议,帮你创建更合适的MySQL索引
IPD process terminology