【netcore基础】MVC API全局异常捕捉中间件ExceptionHandlerMiddleWare
项目中想通过统一的接口格式返回异常信息,而不是404 500等HTTP协议层的异常响应
例如
{
"status":,
"code":,
"message":"用户名或密码不正确",
"detail":"",
"data":null
}
我们需要引用一个异常处理中间件,ExceptionHandlerMiddleWare
代码如下
using GeduData.Server;
using GeduService.Resp;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Serialization; namespace GeduDistributionApi.Extension
{
public class ExceptionHandlerMiddleWare
{
private readonly RequestDelegate next; public ExceptionHandlerMiddleWare(RequestDelegate next)
{
this.next = next;
} public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
} private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
if (exception == null)
{
return;
} await WriteExceptionAsync(context, exception).ConfigureAwait(false);
} private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
{
//返回友好的提示
HttpResponse response = context.Response; //状态码
int nCode = ;
if (exception is GeduException)
{
nCode = ((GeduException)exception).Code;
}
else if (exception is Exception)
{
nCode = ;
} response.ContentType = context.Request.Headers["Accept"]; ExceptionResp resp = new ExceptionResp
{
Status = ,
Code = nCode,
Message = exception.Message,
}; response.ContentType = "application/json";
await response.WriteAsync(JsonConvert.SerializeObject(resp)).ConfigureAwait(false);
} /// <summary>
/// 对象转为Xml
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
private static string Object2XmlString(object o)
{
StringWriter sw = new StringWriter();
try
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
serializer.Serialize(sw, o);
}
catch
{
//Handle Exception Code
}
finally
{
sw.Dispose();
}
return sw.ToString();
} }
}
这里的黄色标注的部分就是我想要接口返回的json对象结构,可自定义
有了这个中间件,我们在Startup.cs里的Configure方法进行配置即可
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
} app.UseCors("AllowSpecificOrigin"); app.MapWhen(
context => context.Request.Path.ToString().EndsWith(".report"),
appBranch => {
appBranch.UseUeditorHandler();
});
app.UseHttpsRedirection(); //异常处理中间件
app.UseMiddleware(typeof(ExceptionHandlerMiddleWare)); app.UseMvc(); //https://localhost:5001/swagger/
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseHangfireServer();
app.UseHangfireDashboard();
app.UseStaticFiles(); }
这样,在接口的业务逻辑里,无论有什么异常抛出,我们都可以统一通过中间件进行处理,返回指定格式的json内容
这里还可以定义自己业务逻辑异常,以便区分系统Exception
爽歪歪
【netcore基础】MVC API全局异常捕捉中间件ExceptionHandlerMiddleWare的更多相关文章
- android中全局异常捕捉
android中全局异常捕捉 只要写代码就会有bug,但是我们要想办法收集到客户的bug.有第三方bugly或者友盟等可以收集.但是,android原生就提供了有关收集异常的api,所以我们来学习一下 ...
- Spring 全局异常捕捉
Spring全局异常捕捉类 注解@ControllerAdvice package com.sicdt.sicsign.web.bill.controller; import org.springfr ...
- springboot(四)拦截器和全局异常捕捉
github代码:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service 全部 ...
- 在Spring Boot中添加全局异常捕捉提示
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...
- NetCore实现全局异常捕捉统一处理
做net项目时候,在Global.asax文件中可以通过Application_Error方法全局捕获异常并处理后统一跳转到自定义的错误页面. 下面是我个人在NetCore项目中实现全局捕获异常并统一 ...
- 5.全局异常捕捉【从零开始学Spring Boot】
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...
- Android全局异常捕捉
// 定义自定义捕捉 package com.xiaosw.test; import java.io.File; import java.io.FileOutputStream; import jav ...
- (5)全局异常捕捉【从零开始学Spring Boot】
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...
- springBoot 全局异常捕捉
package cn.com.cs.core.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import or ...
随机推荐
- java中四舍五入——double转BigDecimal的精度损失问题
代码: double d = -123456789012345.3426;//5898895455898954895989; NumberFormat nf = new DecimalFormat(& ...
- 最小生成树 Prim Kruskal
layout: post title: 最小生成树 Prim Kruskal date: 2017-04-29 tag: 数据结构和算法 --- 目录 TOC {:toc} 最小生成树Minimum ...
- AndroidStudio下加入百度地图的使用 (三)——API基本方法及常量属性
上一章中我们已经完成定位功能,这一章向大家介绍一下常用的方法及常量属性的意思. (1) 手势方法 缩放: setZoomGesturesEnabled() 俯视: setOverlookingGest ...
- 【GPU编解码】GPU硬解码---DXVA (转)
前面介绍利用NVIDIA公司提供的CUVID库进行视频硬解码,下面将介绍利用DXVA进行硬解码. 一.DXVA介绍 DXVA是微软公司专门定制的视频加速规范,是一种接口规范.DXVA规范制定硬件加速解 ...
- 谷歌Chrome浏览器无法安装插件的解决方法
Chrome浏览器已替代了个人多年使用的遨游浏览器,但众所周知,国内的环境无法正常登录谷歌账户.无法访问应用商店,而Chrome主版本号大于66的只能从Chrome应用商店下载并安装插件,这不是死结吗 ...
- ASP.NET Core入门系列教程
微软把这个新的框架叫:Razor Pages,以下文中我们将频繁提及—Razor Pages. 项目目录结构 wwwroot静态资源文件夹首先,Razor Pages项目中多了一个wwwroot的文件 ...
- SpringBoot中配置起动时的数据库初始化角本
一.简介 我们使用SpringBoot + JPA时,需要程序在启动时执行数据表的初始化或者数据库记录的初始化.一般数据表的初始化可以通过在Spring Boot的application.proper ...
- donet core 2.1 DateTime ToString() 方法 在不同平台返回的时间格式不一样?
跟操作系统的 设置的时间格式和系统区域设置有关.为了保持一致性.参数自己写好格式.
- POCO Log库
http://pocoproject.org/index.html 有个想法,把这个所谓的跨平台log库阉割成只支持win的,然后使代码尽量简化,高效,以后有时间就开始研究,哈哈.
- Self-Host
寄宿Web API 不一定需要IIS 的支持,我们可以采用Self Host 的方式使用任意类型的应用程序(控制台.Windows Forms 应用.WPF 应用甚至是Windows Service) ...