当前位置:网站首页>WebApi hits an Attribute to handle exceptions uniformly
WebApi hits an Attribute to handle exceptions uniformly
2022-08-01 01:03:00 【lee576】
When we handle exceptions, we usually write code like the following
try{xxxxx}catch(Exception ex){log.write(ex.Message)}I watched Yang Zhongke's video some time ago, in which I spit out the pipeline mechanism of mvc. Of course, it is better to separate the front and back ends when it is used in the rendering of web ui, because the pipeline and the razor view engine are used to do these things.It is very cumbersome and heavy, and the whole architecture is complicated, but as some AOP processing, the pipeline is very easy to use. Next, an Atrribute exception filter is used to uniformly handle exceptions, so every time there is an exception, you don’t need to writeThe above code is manually captured
using System;using System.Net;using System.Net.Http;using System.Net.Http.Formatting;using System.Web.Http.Filters;namespace HenryMes.WebApi.App_Start{/// /// Exception handling/// public class OnErrorResponseAttribute : ExceptionFilterAttribute{/// ////// /// 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 call timed out" };context.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.RequestTimeout, Content = new ObjectContent(typeof(ErrowMessage), errorObj, new JsonMediaTypeFormatter(), "application/json") };}//..... Here you can return to the client-specific status code according to the needs of the project.If the corresponding exception cannot be found, it will uniformly return the server error 500else{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);}/// ////// public class ErrowMessage{/// ////// public bool Result { set; get; }/// ////// public string Message { set; get; }}}}The above is a filter for exception handling. The following Contronlller only needs to be marked with a label, so there is no need to write try catch again
/// ////// /// [HttpPost][OnErrorResponse]public IHttpActionResult Test(){var aaa = 999;var b = 333;b = 0;var c = aaa / b;return null;}边栏推荐
- Nmap 操作手册 - 完整版
- Introduction to the five data types of Redis
- WindowInsetsControllerCompat简单使用
- Key Points Estimation and Point Instance
- 【密码学/密码分析】基于TMTO的密码分析方法
- pycaret source code analysis: download dataset\Lib\site-packages\pycaret\datasets.py
- 南方科技大学:Xiaoying Tang | AADG:视网膜图像分割领域泛化的自动增强
- In 2022, the latest eight Chongqing construction members (electrical construction workers) simulation question bank and answers
- Compose原理-视图和数据双向绑定的原理
- Redis五种数据类型简介
猜你喜欢

MYSQL主从复制

YOLO怎么入门?怎么实现自己的训练集?

MVCC总结

RTL8762DK PWM (seven)

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

Key Points Estimation and Point Instance

Matlab/ArcGIS processing GPM global monthly precipitation data

【密码学/密码分析】基于TMTO的密码分析方法

MYSQL-批量插入数据
![[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories](/img/7a/278ffada1cc660e7f5c2d7c66fa38e.png)
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories
随机推荐
What is the meaning of JS timestamp?Know SQL will consider to add a timestamp, JS timestamp for the scene?
Web3.0: Building an NFT Market (1)
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories
Rasa 3.x 学习系列-使用查找表改进实体提取
Rasa 3.x Study Series - Rasa - Issues 4918 Study Notes
VPGNet
二叉树遍历非递归程序 -- 使用栈模拟系统栈
WebApi 打个Attribute 统一处理异常
Matlab / ArcGIS 处理GPM全球月均降水数据
两院院士直言:不要迷信院士
How to Design High Availability and High Performance Middleware - Homework
命名实体识别-模型:BERT-MRC
简单的vim配置
Classes and Objects: Above
Item 36: Specify std::launch::async if asynchronicity is essential.
In 2022, the latest eight Chongqing construction members (electrical construction workers) simulation question bank and answers
Modern Enterprise Architecture Framework 1
Classes and Objects: Medium
推荐系统:常用评价指标总结【准确率、精确率、召回率、命中率、(归一化折损累计增益)NDCG、平均倒数排名(MRR)、ROC曲线、AUC(ROC曲线下的面积)、P-R曲线、A/B测试】
MYSQL二阶段提交