server/aspnetapp/Middlewares/CustomerExceptionMiddleware.cs

(完整代码) 1KB

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text.Json;
using System.Threading.Tasks;

namespace aspnetapp.Middlewares
{
    /// <summary>
    /// 自定义异常中间件
    /// </summary>
    public class CustomerExceptionMiddleware
    {
        /// <summary>
        /// 委托
        /// </summary>
        private readonly RequestDelegate _next;

        public CustomerExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                await _next(null).ConfigureAwait(false);
            }
            try
            {
                await _next(context).ConfigureAwait(false);
            }
            catch (Exception ex)
            {

                context.Response.ContentType = "application/problem+json";

                var title = "An error occured: " + ex.Message;
                var details = ex.ToString();

                var problem = new ProblemDetails
                {
                    Status = 200,
                    Title = title,
                    Detail = details
                };

                var stream = context.Response.Body;
                await JsonSerializer.SerializeAsync(stream, problem).ConfigureAwait(false);
            }
        }
    }
}

24 小时内免费解锁 3 个项目,之后 1 算力/个。 规则说明

AI 解读 AI

登录后可用,每次 10 算力,解读结果公开显示在下面。

还没有人解读过这个文件。