项目中想通过统一的接口格式返回异常信息,而不是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. PID控制器(比例-积分-微分控制器)- II

    Table of Contents Practical Process Control Proven Methods and Best Practices for Automatic PID Cont ...

  2. Profiling Java Application with Systemtap

    https://laurent-leturgez.com/2017/12/22/profiling-java-application-with-systemtap/ https://myaut.git ...

  3. float:浮点型double:双精度实型decimal:数字型单精度浮点数(Single)双精度浮点数(double)

        单精度浮点数(Single) 双精度浮点数(double)       Decimal为SQL Server.MySql等数据库的一种数据类型,不属于浮点数类型,可以在定义时划定整数部分以及小 ...

  4. ASP.NET 网站管理工具

    ylbtech-Miscellaneos:ASP.NET 网站管理工具 1. 网站管理工具概述返回顶部 网站管理工具概述 介绍 使用网站管理工具,可以通过一个简单的 Web 界面来查看和管理网站配置. ...

  5. Go语言之高级篇beego框架之view

    1.基本语法 go统一使用了{{ 和 }}作为左右标签,没有其它的标签符号. 如果你想要修改为其它符号,可以修改配置文件. 使用.来访问当前位置的上下文 使用$来引用当前模板根级的上下文 2.使用方法 ...

  6. angular default project (angular.json的解读)

    Change the default Angular project Understanding it's purpose and limits Klaus KazlauskasFollow Nov ...

  7. C# System.Collections.ArrayList

    using System; using System.Collections; public class SamplesArrayList { public static void Main() { ...

  8. IASetIndexBuffer Offset

    这个Offset官方解释是:Offset (in bytes) from the start of the index buffer to the first index to use. 翻译成中文就 ...

  9. C++11 并发指南四(<future> 详解三 std::future & std::shared_future)

    上一讲<C++11 并发指南四(<future> 详解二 std::packaged_task 介绍)>主要介绍了 <future> 头文件中的 std::pack ...

  10. 第三部分:Android 应用程序接口指南---第四节:动画和图形---第一章 属性动画及动画与图形概述

    第1章 属性动画及动画与图形概述 Android提供了一系列强大的API来把动画加到UI元素中,以及绘制自定义的2D和3D图像中去.下面的几节将综述这些可用的API以及系统的功能,同时帮你做出最优的选 ...