【netcore基礎】MVC API全局異常捕捉中間件ExceptionHandlerMiddleWare


項目中想通過統一的接口格式返回異常信息,而不是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);
        }

        /// <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

 

爽歪歪

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM