项目中想通过统一的接口格式返回异常信息,而不是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的更多相关文章

  1. android中全局异常捕捉

    android中全局异常捕捉 只要写代码就会有bug,但是我们要想办法收集到客户的bug.有第三方bugly或者友盟等可以收集.但是,android原生就提供了有关收集异常的api,所以我们来学习一下 ...

  2. Spring 全局异常捕捉

    Spring全局异常捕捉类 注解@ControllerAdvice package com.sicdt.sicsign.web.bill.controller; import org.springfr ...

  3. springboot(四)拦截器和全局异常捕捉

    github代码:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service 全部 ...

  4. 在Spring Boot中添加全局异常捕捉提示

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...

  5. NetCore实现全局异常捕捉统一处理

    做net项目时候,在Global.asax文件中可以通过Application_Error方法全局捕获异常并处理后统一跳转到自定义的错误页面. 下面是我个人在NetCore项目中实现全局捕获异常并统一 ...

  6. 5.全局异常捕捉【从零开始学Spring Boot】

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...

  7. Android全局异常捕捉

    // 定义自定义捕捉 package com.xiaosw.test; import java.io.File; import java.io.FileOutputStream; import jav ...

  8. (5)全局异常捕捉【从零开始学Spring Boot】

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...

  9. springBoot 全局异常捕捉

    package cn.com.cs.core.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import or ...

随机推荐

  1. Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko

    Trident (又称为MSHTML),是微软的窗口操作系统(Windows)搭载的网页浏览器—Internet Explorer的排版引擎的名称. 它的第一个版本随着1997年10月Internet ...

  2. 普通socket与netty服务端交互

    Socket socket = new Socket(host, port);OutputStream out = socket.getOutputStream();ByteBuffer header ...

  3. 你真的会用Gson吗?Gson使用指南(2)

    注:此系列基于Gson 2.4. 上一篇文章 你真的会用Gson吗?Gson使用指南(1) 我们了解了Gson的基础用法,这次我们继续深入了解Gson的使用方法. 本次的主要内容: Gson的流式反序 ...

  4. Android典型界面设计(8) ——ViewPager+PagerSlidingTabStrip实现双导航

    一.问题描述 PagerSlidingTabStrip是android开源项目,指示器控件.官网地址:https://github.com/astuetz/PagerSlidingTabStrip 该 ...

  5. 如何将revit模型背景设置为黑色

    Revit软件建模窗口默认的背景色为白色,在用惯了CAD的新用户转到Revit软件的时候,会对Revit白色的背景不太适应,跟AutoCAD一样,Revit提供自定义工作区背景颜色的功能--其实,你只 ...

  6. windows多线程--原子操作

    推荐参考博客:秒杀多线程第三篇 原子操作 Interlocked系列函数 原子操作 VS 非原子操作 原子操作就是不会被线程调度机制打断的操作,这种操作一旦开始,就一直运行到结束,中间不会有任何线程切 ...

  7. python2判断编码格式

    def getCoding(strInput): ''' 获取编码格式 ''' if isinstance(strInput, unicode): return "unicode" ...

  8. 【PMP】项目和运营的区别

    运营管理关注产品的持续性生产和服务的持续运作. 项目与运营会存在产品生命周期的不同时点交叉,例如: 在产品开发.产品升级或提高产量时: 在改进运营或产品开发流程时: 在产品生命周期结束阶段: 在每个收 ...

  9. orocos_kdl学习(一):坐标系变换

    KDL中提供了点(point).坐标系(frame).刚体速度(twist),以及6维力/力矩(wrench)等基本几何元素,具体可以参考 Geometric primitives 文档. Creat ...

  10. 【C#】详解C#序列化

    目录结构: contents structure [+] 简介 控制序列化和反序列化 特性(OnSerializing.OnSerialized.OnDeserializing.OnDeseriali ...