I am using app.UseExceptionHandler(GlobalErrorHandler) in AspNetCore and after that a custom middleware. When using this separately they work fine but when using them simultaneous the exception is thrown inside my custom middleware and crashes the call. This happens on await _next.Invoke(context). I also tried to use an ExceptionFilter but the results where the same. My global exception handling looks like this. Is there a way to stop the exception from bubbling up?
app.UseCustomMiddleware();
app.UseExceptionHandler(GlobalErrorHandler);
app.UseMvc();
private void GlobalErrorHandler(IApplicationBuilder applicationBuilder)
{
applicationBuilder.Run(
async context =>
{
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
string errorMessage;
var webFault = ex.Error as WebFaultException<string>;
if (webFault != null)
{
context.Response.StatusCode = (int)webFault.StatusCode;
errorMessage = webFault.Detail;
}
else
{
if (ex.Error is UnauthorizedAccessException)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
errorMessage = string.Empty;
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
errorMessage = ex.Error.Message + new StackTrace(ex.Error, true).GetFrame(0).ToString();
}
_logger.Error(errorMessage, ex.Error);
}
await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
}
});
}