I have the following setup in startup.
app.UseStatusCodePagesWithReExecute("/mvc/error/", "?statusCode={0}");
I also have an ExceptionFilter setup using AddMvcCore(). The exception filter is below.
public override void OnException(ExceptionContext context)
{
ApiError apiError;
switch (context.Exception)
{
case ApiException exception:
// handle explicit 'known' API errors
var ex = exception;
context.Exception = null;
apiError = new ApiError(ex.StatusCode, ex.Message) { Messages = ex.Messages };
context.HttpContext.Response.StatusCode = ex.StatusCode;
break;
case UnauthorizedAccessException _:
apiError = new ApiError(401, "Unauthorized Access");
context.HttpContext.Response.StatusCode = 401;
_loggingService.LogError<ApiExceptionFilter>(LogCategory.Api, context.Exception);
break;
default:
// unhandled errors
apiError = new ApiError(500, context.Exception.GetBaseException().Message) { Detail = context.Exception.StackTrace };
context.HttpContext.Response.StatusCode = 500;
_loggingService.LogError<ApiExceptionFilter>(LogCategory.Api, context.Exception);
break;
}
// always return a JSON result
context.Result = new JsonResult(apiError);
base.OnException(context);
}
The problem is when an exception occurs in an action method, the filter kicks in but sends in a JSON result. What I want to do is to bubble the exception up to UseStatusCodePagesWithReExecute middleware as well. Any idea how to do that?
You can't set the result from the action filter if you want to use the status code middleware as well. Take a look at the pre-conditions of the status code middleware in the source code, it will skip the status code page pipeline execution if the response body is already set or have been written to the client.