Files

128 lines
3.8 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApplication1.Controllers;
/// <summary>
/// API 异常过滤器
/// </summary>
class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
public ApiExceptionFilterAttribute()
{
Order = 1;
}
public override void OnException(ExceptionContext context)
{
var ex = context.Exception;
if (ex is PermissionException pex)
{
// 如果为权限异常则修改返回状态码
context.HttpContext.Response.StatusCode = pex.StatusCode;
}
ExceptionResult result;
if (ex is ApiException aex)
{
#if DEBUG
// 调试环境带上堆栈信息
result = new ExceptionResult(aex.ErrorCode, aex.ToString());
#else
result = new ExceptionResult(aex);
#endif
}
else
{
result = new ExceptionResult(ex);
}
context.Result = new JsonResult(result);
context.ExceptionHandled = true;
}
public override Task OnExceptionAsync(ExceptionContext context)
{
OnException(context);
return Task.CompletedTask;
}
}
/// <summary>
/// 页面异常过滤器
/// </summary>
class PageExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
OnExceptionAsync(context).Wait();
}
public override async Task OnExceptionAsync(ExceptionContext context)
{
var ex = context.Exception;
int statusCode = 500;
int errorCode = -1;
string errorMessage;
switch (ex)
{
case ApiException aex:
if (aex is PermissionException pex)
{
// 如果为权限异常则修改返回状态码
statusCode = pex.StatusCode;
}
errorCode = aex.ErrorCode;
errorMessage = errorCode switch
{
ApiException.AUTHORIZED_ERROR => "You are not authorized yet.",
ApiException.PARAMETER_ERROR => "The server could not understand the request due to invalid parameters.",
ApiException.PERMISSION_ERROR => "You have no right to access this page.",
_ => "An unknown error occurred."
};
break;
case System.Net.WebException:
case EndOfStreamException:
errorMessage = "Network connection is failed.";
break;
case TaskCanceledException:
case OperationCanceledException:
errorMessage = "Operation timeout, maybe caused by the network, please try again later.";
break;
default:
errorMessage = "An unknown error occurred.";
break;
}
// deprecated: relative path
//var prefix = context.HttpContext.Request.Path.Value?.Trim('/');
//if (!string.IsNullOrEmpty(prefix))
//{
// int segmentCount = prefix.Split('/', StringSplitOptions.RemoveEmptyEntries).Length;
// prefix = string.Concat(Enumerable.Repeat("../", segmentCount));
//}
var helper = context.HttpContext.RequestServices.GetRequiredService<ViteHelper>();
var html = await helper.RenderAsync(
context.HttpContext.Request.PathBase,
"error.html",
"src/pages/error.ts",
new ApiErrorResult(errorCode, errorMessage),
new() { ["Title"] = "Error Page" });
context.Result = new ContentResult
{
Content = html,
ContentType = "text/html; charset=utf-8",
StatusCode = statusCode
};
context.ExceptionHandled = true;
}
}
record ApiErrorResult(int ErrorCode, string ErrorMessage);