using Long.Core.Api;
using Microsoft.AspNetCore.Http;
using System.Net;
using System.Text.Json;
namespace Long.Core.Middleware;
///
/// 异常捕获中间件
///
public class LongExceptionCatch
{
///
/// 请求委托
///
private readonly RequestDelegate _requestDelegate;
public LongExceptionCatch(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
}
///
/// 唤起
///
///
///
public async Task Invoke(HttpContext httpContext)
{
try
{
await _requestDelegate(httpContext);
}
catch (Exception ex)
{
httpContext.Response.StatusCode = 500;
httpContext.Response.ContentType = "application/json;charset=utf-8";
var result = new LongExceptionOutput()
{
Success = false,
Message = "服务器内部错误:" + ex.Message,
StatusCode = (int)HttpStatusCode.InternalServerError,
Source = ex.Source ?? "",
StackTrace = ex.StackTrace ?? "",
TargetSite = ex.TargetSite,
Data = ex.Data
};
await httpContext.Response.WriteAsync(JsonSerializer.Serialize(result));
}
}
}