当前位置:网站首页>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;
}
边栏推荐
- [1161. The maximum sum of elements in the layer]
- 推荐系统:常用评价指标总结【准确率、精确率、召回率、命中率、(归一化折损累计增益)NDCG、平均倒数排名(MRR)、ROC曲线、AUC(ROC曲线下的面积)、P-R曲线、A/B测试】
- 网关gateway跨域
- TFC CTF 2022 WEB Diamand WriteUp
- GDB source code analysis series of articles five: dynamic library delay breakpoint implementation mechanism
- Matlab / Arcgis处理nc数据
- Introduction to the five data types of Redis
- 微信小程序之小程序页面语法
- What is the meaning of JS timestamp?Know SQL will consider to add a timestamp, JS timestamp for the scene?
- Web API 介绍和类型
猜你喜欢
【Cryptography/Cryptanalysis】Cryptanalysis method based on TMTO
Matlab / ArcGIS 处理GPM全球月均降水数据
微信小程序之小程序页面语法
Carefully summarize thirteen suggestions to help you create more suitable MySQL indexes
NIO programming
JVM面试题总结(持续更新中)
谷歌『云开发者速查表』;清华3D人体数据集;商汤『通用视觉框架』公开课;Web3极简入门指南;高效深度学习免费书;前沿论文 | ShowMeAI资讯日报
MYSQL二阶段提交
cobaltstrike
cmake入门学习笔记
随机推荐
如何设计高可用高性能中间件 - 作业
RTL8762DK UART(二)
LeetCode--The problem of robbery
vim的基本使用-命令模式
MYSQL索引解析
One line of code to solve CoreData managed object properties change in SwiftUI problem of animation effects
sqlserver无法远程连接
Matlab/ArcGIS processing GPM global monthly precipitation data
声称AI存在意识,谷歌工程师遭解雇:违反保密协议
一体化步进电机在无人机自动机场的应用
两院院士直言:不要迷信院士
Team of Professor Chen Jianyu of Tsinghua University | Contact Safety Reinforcement Learning Framework Based on Contact-rich Robot Operation
RTL8762DK WDG(六)
thymeleaf迭代map集合
[微服务]分布式事务解决方案-Seata
RTL8762DK RTC(五)
Matlab/Arcgis processing nc data
力扣二叉树
Web3.0:构建 NFT 市场(一)
thymeleaf iterates the map collection