ExceptionHandler Needed

on Monday, January 27, 2020

As a follow-up to the Create a Custom ProblemDetailsFactory post, it has been discovered that a custom Exception Handler must be defined in order to use the ProblemDetailsFactory. The Exception Handler can be incredibly simple, but it must produce an IActionResult that will trigger the calling of a ProblemDetailsFactory. This can be accomplished with something as simple as this:

The controller only needs to create a Problem IActionResult to trigger the usage your ProblemDetailsFactory.
To ensure that YourBussProblemDetailsFactory is used, you can create two extension functions to use during Startup.cs’s ConfigureServices and Configure methods. That might look like this:

And the extensions functions that provide the wiring would look like the code sample below. Some noticeable pieces in the example are:

  • Within the IServiceCollection extension method, .AddMvc().AddApplicationPart(thisAssembly) is used to ensure that the controller from above is included within the top level application. This is how you can add controllers from sub-libraries.
  • Within the IApplicationBuilder extension method, the final wiring to setup the global exception handler is created to “/your-buss-exception-handler”.
There's an example Exception Detail Converter in a follow-up post (ExceptionDetailConverter Example).

4 comments:

alan said...

In the AddYourBussErrorAndValidationHandling method you use IYourBussApiExceptionDetailConverter and YourBussApiExceptionDetailConverter. Can you show the code for those please?

EVP said...

+1 on having interest in that missing code (DetailConverter).

Also - while I was able to successfully implement this, I observe in my logs that I'm still getting an Error-Level log entry for my business exception being uncaught. Is there a reason why the ProblemDetails factory isn't catching/handling the exception?

smaglio81 said...

Thanks for asking there is a follow up post with an example detail converter: https://stevenmaglio.blogspot.com/2020/04/exceptiondetailconverter-example.html

smaglio81 said...

Thanks for the reminder, I forgot to link to the example detail converter (https://stevenmaglio.blogspot.com/2020/04/exceptiondetailconverter-example.html).

I’m not 100% certain why it logs it as an uncaught exception. I can rationalize it as an uncaught exception because it’s not being caught by “our” code. Instead it’s being “caught/handled” by Microsoft framework code, which seems to be trying to format the exception for serialization purpose. So, the framework code isn’t really trying to handle it gracefully; it’s just trying the serialize the exception information in the most meaningful way for your client applications.

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.