当前位置:网站首页>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;
}边栏推荐
- Rainbow share | how to use moving targets defense technology to guard against the unknown
- sqlserver无法远程连接
- RTL8762DK WDG(六)
- Keil nRF52832 download failed
- Classes and Objects: Above
- 二叉树遍历非递归程序 -- 使用栈模拟系统栈
- Basic use of vim - bottom line mode
- [MATLAB project combat] LDPC-BP channel coding
- 简单的vim配置
- Inheritance and friend, static member relationship
猜你喜欢

Redis五种数据类型简介

类和对象:上

zeno使用方法笔记

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

Matlab/ArcGIS processing GPM global monthly precipitation data

ECCV2022 Workshop | 复杂环境中的多目标跟踪和分割

vector的基本实现

Team of Professor Chen Jianyu of Tsinghua University | Contact Safety Reinforcement Learning Framework Based on Contact-rich Robot Operation

MYSQL-批量插入数据
![[Microservice] Distributed Transaction Solution - Seata](/img/a8/fc6c24e4d42dfb635bad786cc02164.png)
[Microservice] Distributed Transaction Solution - Seata
随机推荐
Compose principle - the view and the principle of two-way data binding
Item 36: Specify std::launch::async if asynchronicity is essential.
RTL8762DK 点灯/LED(三)
Design the message queue storage MySQL form of message data
简单的vim配置
欧拉系统(euleros):升级Mysql
vim的基本使用-底行模式
虹科分享|如何用移动目标防御技术防范未知因素
Super like the keyboard made from zero, IT people love it
VPGNet
Kyoto University: Masaki Waga | Dynamic Masking for Reinforcement Learning in Black Box Environments
Exam preparation plan
Difference between first and take(1) operators in NgRx
Binary tree traversal non-recursive program -- using stack to simulate system stack
Web API Introduction and Types
开源好用的 流程图绘制工具 drawio
Carefully organize 16 MySQL usage specifications to reduce problems by 80% and recommend sharing with the team
MYSQL主从复制
【Cryptography/Cryptanalysis】Cryptanalysis method based on TMTO
Blueprint: Yang Hui's Triangular Arrangement