博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【netcore基础】MVC API全局异常捕捉中间件ExceptionHandlerMiddleWare
阅读量:6946 次
发布时间:2019-06-27

本文共 3836 字,大约阅读时间需要 12 分钟。

项目中想通过统一的接口格式返回异常信息,而不是404 500等HTTP协议层的异常响应

例如

{    "status":0,    "code":0,    "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 = 0;            if (exception is GeduException)            {                nCode = ((GeduException)exception).Code;            }            else if (exception is Exception)            {                nCode = 500;            }            response.ContentType = context.Request.Headers["Accept"];            ExceptionResp resp = new ExceptionResp            {                Status = 0,                Code = nCode,                Message = exception.Message,            };            response.ContentType = "application/json";            await response.WriteAsync(JsonConvert.SerializeObject(resp)).ConfigureAwait(false);        }        ///         /// 对象转为Xml        ///         ///         /// 
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

 

爽歪歪

 

转载地址:http://szenl.baihongyu.com/

你可能感兴趣的文章
GoJS教程[2019]:使用GraphObjects构建零件
查看>>
Java锁细节整理
查看>>
php编译安装
查看>>
正则介绍及grep/egrep用法
查看>>
锚定比特币现金(BCH),助力构建价值互联网时代
查看>>
微服务测试之接口测试和契约测试
查看>>
.NET的数学库NMath实用教程——创建复数的几种方法
查看>>
iOS-LinkLabel
查看>>
创建一个自己的MVC框架
查看>>
Docker | 第一章:Docker简介
查看>>
OSChina 周三乱弹 —— 你会 3P 吗?【PHP,JSP 和 ASP】
查看>>
OSChina 周三乱弹 ——你最想在墓碑上被写些什么
查看>>
openjdk 7编译记录
查看>>
数据结构 ConcurrentHashMap
查看>>
spring boot 初始化是怎么扫描类的
查看>>
css3实现圆形进度条
查看>>
C++学习需要看的书籍
查看>>
jQuery的常用方法
查看>>
mysql联查时为空补全和jdbc获取最后插入生成的id
查看>>
[Android] ArcFace人脸识别 Demo
查看>>