我用异常过滤器解决了这个问题
type ApiError = {
ErrorType: Type
Message: string
StackTrace: string
}
type ApiExceptionAttribute(logger: ILog) =
inherit ExceptionFilterAttribute()
static let [<Literal>] Tag = "ApiExceptionAttribute"
override __.OnException(context) =
base.OnException context
context.HttpContext.Response.StatusCode <-
match context.Exception with
| As (_: UnauthorizedAccessException) -> HttpStatusCode.Unauthorized |> int
| _ -> HttpStatusCode.InternalServerError |> int
let ex = context.Exception.GetBaseException()
let apiError = {
ErrorType = ex.GetType()
Message = ex.Message
StackTrace = ex.StackTrace
}
logger.Error Tag (apiError.ToString()) (Some ex)
context.Result <- JsonResult apiError
然后,按照标准实践,我在
Startup.fs
文件:
在我的startup.fs文件中:
services.AddMvc(fun config ->
config.RespectBrowserAcceptHeader <- true
config.Filters.Add<ApiExceptionAttribute>() |> ignore
) |> ignore
这解决了我的误报,并允许我跟踪和修复代码中的错误。