【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 ...
随机推荐
- keybd_event 被 SendInput 替代
keybd_event 函数功能:该函数合成一次击键事件.系统可使用这种合成的击键事件来产生WM_KEYUP或WM_KEYDOWN消息,键盘驱动程序的中断处理程序调用keybd_event函数.在 ...
- centos7 apache设置伪静态 开启rewrite_module
设置伪静态除了要生成.htaccess文件外,还需要查看服务器是否开启了rewrite_module.经过一番的纠结,处理方法如下: 编辑Apache配置文件 nano /etc/httpd/conf ...
- android:如何通过自定义工程模板让新建的工程都默认支持lambda表达式
首先参考这篇文章:自定义Android Studio工程模板,了解如何自定义模板 然后结合我们上一篇文章 android: 在android studio中使用retrolambda的步骤的要点, ...
- shell中函数返回值
1.前言 快半年没有写博客了,荒废了很久,工作中的杂事太多,自己越来越懒了.为了鞭策自己成长,还是要坚持写写博客,记录自己的成长. 2.shell函数介绍 语法: [ function ] funna ...
- Spark2.2+ES6.4.2(三十二):ES API之index的create/update/delete/open/close(创建index时设置setting,并创建index后根据avro模板动态设置index的mapping)
要想通过ES API对es的操作,必须获取到TransportClient对象,让后根据TransportClient获取到IndicesAdminClient对象后,方可以根据IndicesAdmi ...
- ASP.net教程]启用WebApi 2里的Api描述信息(Help下的Description
环境:vs2013+web api 2 问题:默认情况下新建的Web Api 2项目,自带的Help页下会显示Api的相关信息,但Description那一栏无法获取到数据,如下图所示: 解决: 1. ...
- android makefile文件批量拷贝文件的方法
该方法是shell 和makefile组合使用 wallpapers := $(shell ls packages/apps/hyst_apps/NewBingoLauncher_C/default_ ...
- 开发指南专题五:JEECG微云高速开发平台代码生成器
开发指南专题五:JEECG微云高速开发平台代码生成器 1.1. Maven开发环境搭建 在搭建jeecg的maven开发环境之前,须要先配置好本机的maven环境,并在eclipse中安装好m2ecl ...
- CPP Note
hello.cpp -> 编译代码g++ hello.cpp -o a -> a.out 区分大小写的编程语言 内置类型 一些基本类型可以使用一个或多个类型修饰符进行修饰: signed: ...
- 看不见的攻击面:查看 SQLite 数据库就中招?
Navicat 客户端存在一个 XSS,在查看表字段时,没有对内容进行处理,导致一个 XSS 问题.利用这个漏洞可以读取敏感文件,比如 /Users/XXXX/.bash_history . 漏洞发现 ...