Allow ExceptionHandlerOptions.ExceptionHandler to be called even if the response has started
See original GitHub issueIs your feature request related to a problem? Please describe.
I am trying to set up error handling for my application. When an error occurs, I want to POST it to an error tracking service we use. I was going to use ExceptionHandlerMiddleware for this with a custom ExceptionHandlerOptions.ExceptionHandler, but reading through the source of ExceptionHandlerMiddleware I noticed that the delegate won’t even be invoked if the response has started. This is a downside since we have some endpoints that export very large, dynamically generated files in a streaming fashion so something really can go wrong after the response starts and we want to know.
Describe the solution you’d like
I’d like it if there were a way to have the handler called anyway even if the response has started (e. g. specified through a flag on the options).
Describe alternatives you’ve considered
(1) I could not not use ExceptionHandlerMiddleware and write my own middleware instead. ExceptionHandlerMiddleware does a bunch of stuff with registering features and such; it’s not clear to me how important that is.
(2) Since ExceptionHandlerMiddleware does a rethrow when the response has started, it seems like I could put a custom piece of middleware before the main exception handler to catch this case. I’d probably prefer to just go with (1), though.
Additional context
I’m curious if most users of the framework are even aware of this behavior. Had I not happened to look at the source, I never would have guessed that it did this.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (4 by maintainers)

Top Related StackOverflow Question
The
ExceptionHandlerMiddlewarelogic (not running if the request has started) seems by-design to me. Since it’s supposed to handle exceptions, it can’t really do that if the response has already started (otherwise it would insert whatever content it’s using to handle the exception in mid-stream). A middleware of your own (just atry...catchwrapped aroundnext) could work here, or theDiagnosticListeneroption @davidfowl mentioned.Moving to Discussions since we don’t have plans to add this functionality to
ExceptionHandlerMiddleware. If some work comes out of this discussion we can always adjust or file new issues 😃.Thank you for contacting us. Due to a lack of activity on this discussion issue we’re closing it in an effort to keep our backlog clean. If you believe there is a concern related to the ASP.NET Core framework, which hasn’t been addressed yet, please file a new issue.
This issue will be locked after 30 more days of inactivity. If you still wish to discuss this subject after then, please create a new issue!