我为我的API编写了一个异常过滤器来处理API中引发的异常:
using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiExceptionFilter : ExceptionFilterAttribute {
public override void OnException(ExceptionContext context) {
// First, generate the status code based on the exception type
HttpStatusCode status = context.Exception switch {
UnauthorizedAccessException => HttpStatusCode.Unauthorized,
ArgumentException => HttpStatusCode.BadRequest,
MissingHeaderException => HttpStatusCode.BadRequest,
NotFoundException => HttpStatusCode.NotFound,
_ => HttpStatusCode.InternalServerError,
};
// Next, inject the status code and exception message into
// a new error response and set the result with it
context.Result = new JsonResult(new ErrorResponse {
StatusCode = status,
Message = context.Exception.Message
});
// Finally, call the base function
base.OnException(context);
}
}
这个函数按预期拦截异常,但我遇到的问题是它总是返回一个OK响应。如何确保响应包含异常消息并且响应代码是非200值?