当前位置:网站首页>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;}
边栏推荐
猜你喜欢
随机推荐
Likou Binary Tree
Rainbow share | how to use moving targets defense technology to guard against the unknown
RTL8762DK PWM(七)
MYSQL事务
MYSQL查询截取优化分析
Item 36: Specify std::launch::async if asynchronicity is essential.
Introduction to the five data types of Redis
两院院士直言:不要迷信院士
JQESAP系统里的胖接口Fat interface
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
vim的基本使用-底行模式
Nmap 操作手册 - 完整版
MYSQL-批量插入数据
Academicians of the two academies speak bluntly: Don't be superstitious about academicians
精心总结十三条建议,帮你创建更合适的MySQL索引
When can I use PushGateway
Kyoto University: Masaki Waga | Dynamic Masking for Reinforcement Learning in Black Box Environments
【历史上的今天】7 月 31 日:“缸中之脑”的提出者诞生;Wi-Fi 之父出生;USB 3.1 标准发布
Key Points Estimation and Point Instance
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories