项目中想通过统一的接口格式返回异常信息,而不是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. 端口转发工具rinetd的安装与配置

    端口映射和转发在实际应用中非常常见,比如一个局域网只有一台服务器可以被互联网访问到,那么如果想通过互联网访问局域网中其他的服务,最常用的方式就是在这一台机器上开放端口,然后转发至局域网中其他主机的端口 ...

  2. 使用SpringBoot配置了 server.servlet.path后无效的解决方案

    一.问题描述 使用SpringBoot配置了 server.servlet.path后无效,访问时无法通过:http://127.0.0.1:8080/app/hello.html 访问. 二.解决方 ...

  3. c++11 简明学习

    https://coolshell.cn/articles/5265.html http://www.cnblogs.com/me115/p/4800777.html#h29 https://chan ...

  4. http头文件User-Agent详解【转载】

    原文地址:http://blog.csdn.net/andybbc/article/details/50587359 http头文件User-Agent详解 什么是User-Agent User-Ag ...

  5. sed 简明教程 (转)

    sed 简明教程 2013年2月20日   awk于1977年出生,今年36岁本命年,sed比awk大2-3岁,awk就像林妹妹,sed就是宝玉哥哥了.所以 林妹妹跳了个Topless,他的哥哥sed ...

  6. struts2 + urlrewrite 整合注意事项

    这几天业余时间在玩百度云,百度的云还是不错的,但是对于我这样的.NET程序员,有点不公平,没有.net虚机,不过也不是百度一家没有,基本都没有,有的都是那种开放云,自已在云端来部署安装软件的. 所以也 ...

  7. mac mini纯键盘操作连接蓝牙鼠标

    许久不开家里的MAC MINI了,今天开来玩玩,结果进个桌面连接鼠标就费了好大的劲 现实情况: 1. 没有有线鼠标,只有一个USB键盘,一个微软3600蓝牙鼠标 MAC MINI连接上USB键盘,开机 ...

  8. [svc]对称加密/非对称加密细枝末节-如何做到数据传输的authentication/data integrity/confidentiality(私密)

    对称/非对称/混合加密的冷知识 数据在互联网上传输,要考虑安全性. 讲到安全,要从三方面考虑: 1.authentication 每一个IP包的认证,确保合法源的数据 2.data integrity ...

  9. 物联网架构成长之路(20)-申请免费SSL证书

    0.前言 今天域名备案申请下来了,接下来就是申请个SSL证书,现在普通的网站没有SSL都不好意思见人了.可是稍微好点的企业级SSL证书还是比较贵的.不过还好有免费的可以用.只不过要定时去续时间.这个不 ...

  10. java框架篇---hibernate之连接池

    Hibernate支持第三方的连接池,官方推荐的连接池是C3P0,Proxool,以及DBCP.在配置连接池时需要注意的有三点: 一.Apche的DBCP在Hibernate2中受支持,但在Hiber ...