62 lines
2.3 KiB
C#
62 lines
2.3 KiB
C#
using iFileProxy.Helpers;
|
|
using iFileProxy.Models;
|
|
using Serilog;
|
|
using System.Net;
|
|
using System.Text.Json;
|
|
|
|
namespace iFileProxy.Middlewares
|
|
{
|
|
public class ErrorHandlerMiddleware(RequestDelegate next)
|
|
{
|
|
private readonly RequestDelegate _next = next;
|
|
|
|
private readonly static ILogger _logger = Log.Logger.ForContext<ErrorHandlerMiddleware>();
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
if (context.Response.HasStarted)
|
|
{
|
|
_logger.Debug($"响应已经开始,无法再修改其响应内容");
|
|
return;
|
|
}
|
|
if (context.Response.StatusCode == 404)
|
|
{
|
|
context.Response.ContentType = "application/json";
|
|
await context.Response.WriteAsync(JsonSerializer.Serialize(new CommonRsp { Retcode = 404, Message = "你正在请求的资源不存在!" }));
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await HandleExceptionAsync(context, ex);
|
|
}
|
|
}
|
|
|
|
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
|
|
{
|
|
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
|
|
_logger.Error("崩溃数据: {exception}\n上下文信息: {context}", exception, JsonSerializer.Serialize(MasterHelper.ExtractDebugInfo(context)));
|
|
switch (exception)
|
|
{
|
|
|
|
case NotImplementedException:
|
|
code = HttpStatusCode.NotImplemented; // 501
|
|
break;
|
|
case UnauthorizedAccessException:
|
|
code = HttpStatusCode.Unauthorized; // 401
|
|
break;
|
|
case ArgumentException:
|
|
code = HttpStatusCode.BadRequest; // 400
|
|
break;
|
|
// Add more cases for different types of exceptions
|
|
}
|
|
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = (int)code;
|
|
|
|
return context.Response.WriteAsync(JsonSerializer.Serialize(new CommonRsp { Retcode = 1, Message = "server internal error" }));
|
|
}
|
|
}
|
|
}
|