【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 ...
随机推荐
- wordpress模板修改及函数说明
原文:http://java-er.com/blog/wp-mb-edit/ WordPress基本模板文件 style.css : CSS(样式表)文件index.php : 主页模板archive ...
- JavaScript 空间分析库——JSTS和Turf【转】
https://blog.csdn.net/neimeng0/article/details/80363468 前言 项目中有管线的空间拓扑关系查询需求,在npm中检索到JSTS和Turf两个Java ...
- 数据库 简介 升级 SQLite 总结 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- MDX Cookbook 02 - 除数为零的问题
先直接看一个例子 - WITH MEMBER [Date].[Calendar Year].[CY 2006 vs 2005 Bad] AS ], FORMAT_STRING = 'Percent' ...
- vue中使用some删除list中的数据
在vue中可以使用some方法查找需要删除的所以 this.list.some((item, i) => { if (item.id == id) { this.list.splice(i, 1 ...
- void android.graphics.Bitmap.recycle()
void android.graphics.Bitmap.recycle() Free up the memory associated with this bitmap's pixels, and ...
- java多线程状态
造成线程进入阻塞状态的情况大致可分为: 1.调用sleep()方法 2.调用阻塞式IO方法 3. 4.等待通知 5.调用suspend(),程序挂起.
- android开发的童鞋们 你该学点C++
更多关于C++的知识点,请关注android开发应该学点C++(索引贴)android开发应该学点C++(其他) (*android开发论坛----android开发学习----android开发*) ...
- Linux查看CPU和内存的配置信息
CPU配置信息:frank@ubuntu:~/test/python$ cat /proc/cpuinfo processor : #系统中逻辑处理核的编号 vendor_id : GenuineIn ...
- 如何解决:对应的服务器 tls 为 tls 1.0,小程序要求的TLS版本必须大于等于1.2问题
微信小程序 TLS 版本必须大于等于1.2问题解决 此问题最近在微信小程序开发中,比较常见. 在解决这个问题之前,我们需要了解一下,当前的系统环境是否支持TLS1.2以上,可以参考一下表格: 请先确认 ...