当前位置:网站首页>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;
}
边栏推荐
- Application of integrated stepper motor in UAV automatic airport
- Automated machine learning pycaret: PyCaret Basic Auto Classification LightGBM
- /etc/sysconfig/network-scripts configure the network card
- RTL8762DK RTC(五)
- Luogu P3373: 线段树
- 【读书笔记->数据分析】02 数据分析准备
- Keil nRF52832 download failed
- 力扣2326、197
- Nmap 操作手册 - 完整版
- Recommendation system: Summary of common evaluation indicators [accuracy rate, precision rate, recall rate, hit rate, (normalized depreciation cumulative gain) NDCG, mean reciprocal ranking (MRR), ROC
猜你喜欢
[1161. The maximum sum of elements in the layer]
自动化机器学习pycaret: PyCaret Basic Auto Classification LightGBM
两院院士直言:不要迷信院士
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories
MYSQL经典面试题
VPGNet
RTL8762DK WDG(六)
RTL8762DK UART(二)
Kyoto University: Masaki Waga | Dynamic Masking for Reinforcement Learning in Black Box Environments
STK8321 I2C(昇佳-加速度传感器)示例
随机推荐
qlib量化源码分析:qlib/qlib/contrib/model/gbdt.py
Recommendation system: Summary of common evaluation indicators [accuracy rate, precision rate, recall rate, hit rate, (normalized depreciation cumulative gain) NDCG, mean reciprocal ranking (MRR), ROC
WeChat applet page syntax
Google "Cloud Developer Quick Checklist"; Tsinghua 3D Human Body Dataset; SenseTime "Universal Vision Framework" open class; Web3 Minimalist Getting Started Guide; Free Books for Efficient Deep Learni
Basic use of vim - bottom line mode
[Microservice] Distributed Transaction Solution - Seata
[MATLAB project combat] LDPC-BP channel coding
RTL8762DK PWM(七)
500 miles
LeetCode--The problem of robbery
SVN server construction + SVN client + TeamCity integrated environment construction + VS2019 development
mysql having的用法
南方科技大学:Xiaoying Tang | AADG:视网膜图像分割领域泛化的自动增强
Matlab/Arcgis processing nc data
RTL8762DK RTC(五)
Web3.0: Building an NFT Market (1)
Usage of mysql having
TFC CTF 2022 WEB Diamand WriteUp
When can I use PushGateway
Notes on how to use zeno