当前位置:网站首页>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;}
边栏推荐
- MYSQL索引解析
- Js replication
- Team of Professor Chen Jianyu of Tsinghua University | Contact Safety Reinforcement Learning Framework Based on Contact-rich Robot Operation
- WeChat applet page syntax
- When can I use PushGateway
- Cmake introductory study notes
- SC7A20(士兰微-加速度传感器)示例
- Classes and Objects: Above
- Compose principle - the view and the principle of two-way data binding
- sqlserver无法远程连接
猜你喜欢
【历史上的今天】7 月 31 日:“缸中之脑”的提出者诞生;Wi-Fi 之父出生;USB 3.1 标准发布
LeetCode每日一练 —— 环形链表问题(面试四连问)
pycaret source code analysis: download dataset\Lib\site-packages\pycaret\datasets.py
力扣二叉树
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories
leetcode: 1648. Color ball with decreasing sales value [Boundary find by two points]
/etc/sysconfig/network-scripts configure the network card
RTL8762DK 使用DebugAnalyzer(四)
欧拉系统(euleros):升级Mysql
STK8321 I2C(昇佳-加速度传感器)示例
随机推荐
RTL8762DK Lighting/LED (3)
Difference between first and take(1) operators in NgRx
【Cryptography/Cryptanalysis】Cryptanalysis method based on TMTO
蓝图:杨辉三角排列
Matlab / Arcgis处理nc数据
STK8321 I2C(昇佳-加速度传感器)示例
SC7A20(士兰微-加速度传感器)示例
你需要知道的 TCP 四次挥手
Js replication
命名实体识别-模型:BERT-MRC
RTL8762DK 点灯/LED(三)
Item 36: Specify std::launch::async if asynchronicity is essential.
声称AI存在意识,谷歌工程师遭解雇:违反保密协议
Academicians of the two academies speak bluntly: Don't be superstitious about academicians
继承的注意事项
一行代码解决CoreData托管对象属性变更在SwiftUI中无动画效果的问题
【密码学/密码分析】基于TMTO的密码分析方法
MYSQL索引解析
一体化步进电机在无人机自动机场的应用
MYSQL逻辑架构