Pragmatic error handling
A simple and practical approach to error management.
I’ll explore some patterns and antipatterns regarding creating, throwing, and handling exceptions. These are the most common problems I’ve encountered before.
Don’t centralize — Avoid exception hierarchies
Inheritance is often abused in the object-oriented paradigm, which includes exception modeling. However, there’s no benefit to resorting to inheritance to model exceptions. This is worsened when people create hierarchies thinking about the future… Grouping exceptions by type creates unnecessary coupling and complexity.
Unnecessary exception hierarchy:
Exception
↖ MyAppException
↖ InputError
↖ CheckoutException
↖ CartException
↖ EmptyCart
↖ CartNotFound
↖ CantProcessOrder
↖ OrderNotFound
...
Instead, inherit directly from Exception and catch specific exceptions; probably, the handling is different per exception anyway, depending on the use case; if it’s the same, maybe you just needed one exception in the first place (a “multi-catch” also hints that).