Name Exceptions After The Problem
It’s possible to do strange things with exceptions. Problems occur when developers misunderstand a programming concept or how to use it. Today I’ll explore one such misconception regarding exceptions, and then I’ll clear it up.
Let’s get into it.
Recently I came across some validation code that had me perplexed: This code was throwing HttpStatusExceptions
yet, there was no HTTP Status to check. In this section, there was no interaction with an HTTP Service. These HttpStatusExceptions
looked a bit like this:
throw new HttpStatusException("The first name is missing.", 400);
I surmised that the first argument was an error message and the second the HTTP Status code; here 400 – Bad Request.
But what was going on? In every instance where the author decided to throw HttpStatusException
, there was no HTTP activity. Strange indeed.
Finally, I got it: The authoring developer had named the exception, not for the error condition, but after how they wanted the problem handled. When the first name was missing, they wanted this to be communicated as an HTTP 400 error response to the client. OK, this made some sense since the system was an HTTP API.
However, naming custom exceptions to describe how they should be handled is a mistake, an anti-pattern.
Why?
Loss Of Flexibility—By prescribing how an error ought to be managed at the point where the error occurs means we lose the flexibility of controlling the error differently. Throwing an HttpStatusException in a Web API seems to make sense. However, it would make little sense in a non-web context, like a console app or Desktop app. As a result, the validation code throwing HttpStatusException
s, has become immovable—it cannot be moved or hosted in anything but a Web API.
The recommendation is to name custom exceptions after the problem: e.g.
InvalidPaymentGateway
,MissingClientName
,InvalidEmailAddressFormat
, etc.
These exceptions have informative names, explaining the problem clearly. And best of all, we have complete freedom as to how we want to handle them.
So, please name exceptions after the problem, not how you see them managed.
Leave a Reply
Want to join the discussion?Feel free to contribute!