Pragmatic error handling

A simple and practical approach to error management.

Luís Soares
CodeX

--

Photo by Sigmund on Unsplash

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).

Don’t centralize — Beware of technical hotspots

--

--

Luís Soares
CodeX
Writer for

I write about automated testing, Lean, TDD, CI/CD, trunk-based dev., user-centric dev, domain-centric arch, coding good practices,