首页 > 编程语言 >Asp.net Core 全局异常处理

Asp.net Core 全局异常处理

时间:2023-03-23 17:25:11浏览次数:54  
标签:Core Asp 中间件 next code ex context net message

中间件方式

  1. 建立中间件处理类
  2. Startup.cs 中注册
  3. 任何Controller中的Action抛出异常均可被捕捉

在项目根目录下自建目录Middleware
image

新建中间件类ErrorHandlerMiddleware

using Newtonsoft.Json;
using System.Net;
using Uap.Exceptions;

namespace Uap.Middleware
{
    /// <summary>
    /// 全局错误处理中间件
    /// </summary>
    public class ErrorHandlerMiddleware
    {
        private readonly RequestDelegate next;

        public ErrorHandlerMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            var code = 0;
            var message = "Unknown error";

            // BadHttpRequestException,请求类错误
            // ServiceException,自定义的后端处理类错误

            if (ex is BadHttpRequestException)
            {
                code = ((BadHttpRequestException)ex).StatusCode;
                message = ex.Message;
            }
            else if (ex is ServiceException)
            {
                code = (int)((ServiceException)ex).StatusCode;
                message = ex.Message;
            }
            else
            {
                code = (int)HttpStatusCode.InternalServerError;
                message = "Internal server error";
            }

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = code;
            return context.Response.WriteAsync(JsonConvert.SerializeObject(new { message = message }));
        }
    }
}

引用

ASP.NET Core Web API通过中间件或UseExceptionHandler异常处理方法

标签:Core,Asp,中间件,next,code,ex,context,net,message
From: https://www.cnblogs.com/cinlap/p/17248203.html

相关文章