using Microsoft.AspNetCore.Http;
|
using Newtonsoft.Json;
|
using System;
|
using System.Collections.Generic;
|
using System.DirectoryServices.Protocols;
|
using System.Linq;
|
using System.Net;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace WIDESEA_Core.Middlewares
|
{
|
public class ExceptionHandlerMiddleware
|
{
|
private readonly RequestDelegate _next;
|
|
public ExceptionHandlerMiddleware(RequestDelegate next)
|
{
|
_next = next;
|
}
|
|
/// <summary>
|
/// 处理HTTP请求并捕获异常
|
/// </summary>
|
/// <param name="context">HTTP上下文</param>
|
/// <returns>表示异步操作的任务</returns>
|
/// <remarks>
|
/// 当请求处理过程中发生异常时,会调用HandleExceptionAsync方法进行处理
|
/// </remarks>
|
public async Task Invoke(HttpContext context)
|
{
|
try
|
{
|
await _next(context);
|
}
|
catch (Exception ex)
|
{
|
await HandleExceptionAsync(context, ex);
|
}
|
}
|
|
/// <summary>
|
/// 异步处理异常并写入响应
|
/// </summary>
|
/// <param name="context">HTTP上下文</param>
|
/// <param name="e">待处理的异常对象</param>
|
/// <returns>表示异步操作的任务</returns>
|
private async Task HandleExceptionAsync(HttpContext context, Exception e)
|
{
|
if (e == null) return;
|
|
await WriteExceptionAsync(context, e).ConfigureAwait(false);
|
}
|
|
/// <summary>
|
/// 异步将异常信息写入HTTP响应
|
/// </summary>
|
/// <param name="context">HTTP上下文对象</param>
|
/// <param name="e">发生的异常</param>
|
/// <remarks>
|
/// 根据异常类型设置对应的HTTP状态码:
|
/// - UnauthorizedAccessException: 返回401未授权状态码
|
/// - 其他异常: 返回500内部服务器错误状态码
|
/// 响应内容为JSON格式的错误信息
|
/// </remarks>
|
private static async Task WriteExceptionAsync(HttpContext context, Exception e)
|
{
|
var message = e.Message;
|
switch (e)
|
{
|
case UnauthorizedAccessException:
|
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
break;
|
default:
|
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
break;
|
}
|
context.Response.ContentType = "application/json";
|
await context.Response
|
.WriteAsync(JsonConvert.SerializeObject(WebResponseContent.Instance.Error(message)))
|
.ConfigureAwait(false);
|
}
|
}
|
}
|