当前位置:网站首页>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;}边栏推荐
- C字符串数组反转
- Introduction to the five data types of Redis
- 【Cryptography/Cryptanalysis】Cryptanalysis method based on TMTO
- /etc/sysconfig/network-scripts configure the network card
- vim的基本使用-命令模式
- RTL8762DK PWM (seven)
- 南方科技大学:Xiaoying Tang | AADG:视网膜图像分割领域泛化的自动增强
- [AMEX] LGBM Optuna American Express Credit Card Fraud Contest kaggle
- Rasa 3.x 学习系列- Rasa - Issues 4918 学习笔记
- One line of code to solve CoreData managed object properties change in SwiftUI problem of animation effects
猜你喜欢

MYSQL关键字Explain解析

Classes and Objects: Medium

【MATLAB项目实战】LDPC-BP信道编码

Matlab / Arcgis处理nc数据

Matlab / ArcGIS 处理GPM全球月均降水数据

Automated machine learning pycaret: PyCaret Basic Auto Classification LightGBM

清华大学陈建宇教授团队 | 基于接触丰富机器人操作的接触安全强化学习框架

Unity3D学习笔记10——纹理数组

Key Points Estimation and Point Instance

ROS2系列知识(4): 理解【服务】的概念
随机推荐
Interview Question: Implementing Deadlocks
Named Entity Recognition - Model: BERT-MRC
类和对象:上
Force buckle 2326, 197
vim的基本使用概念
Automated machine learning pycaret: PyCaret Basic Auto Classification LightGBM
MYSQL索引解析
【密码学/密码分析】基于TMTO的密码分析方法
清华大学陈建宇教授团队 | 基于接触丰富机器人操作的接触安全强化学习框架
Kyoto University: Masaki Waga | Dynamic Masking for Reinforcement Learning in Black Box Environments
MVCC总结
虚继承的原理
Academicians of the two academies speak bluntly: Don't be superstitious about academicians
Nmap 操作手册 - 完整版
TFC CTF 2022 WEB Diamand WriteUp
Blueprint: Yang Hui's Triangular Arrangement
Rasa 3.x 学习系列- Rasa - Issues 4898 学习笔记
考研备考方案
[Microservice] Distributed Transaction Solution - Seata
TFC CTF 2022 WEB Diamand WriteUp