Today, I’ll share a short but interesting question (and my answer to it) about error mapping.
Here’s the question itself:
Let’s say the domain model returns an error that should not be leaked to the user, so you map it or clean it to remove sensitive data. Should that happen in the domain layer, or in the controller (the application layer)?
It seems cleaner to put it in the controller as that’s where all this stuff is done… but, it feels like a domain issue.
It’s quite a typical use case. The most common example is when the application validates the username and password when logging in the user.
There could be multiple validation errors in this scenario, including:
The user is not found in the database
The username doesn’t comply with basic validation rules (e.g. it’s too short)
The password is incorrect, etc
For security reasons, you can’t display the exact validation error to the user. All you can show is the genetic "username or password is invalid".
Where should that mapping from the specific to the generic error go? In the domain or application layer?
It should go to the domain layer.
The cleaning/error mapping is a domain concern. It originates from the business requirement, which means it should be part of the domain.
Introduce a separate domain class like
ErrorCleaner, or similar.
This would not only put this logic where it belongs, it would also simplify the controller and improve testability: it’s much easier to unit test a method with a single
Error argument, than a whole controller working with multiple out-of-process dependencies.
That’s by the way the essence of the Humble Object pattern. The idea is to extract an important piece of logic (the error mapper) out of controllers in order to ease up unit testing of that logic.
Enjoy this message? Here are more things you might like:
Workshops — I offer a 2-day workshop for organizations on Domain-Driven Design and Unit Testing. Reply to this email to discuss.
Unit Testing Principles, Patterns and Practices — A book for people who already have some experience with unit testing and want to bring their skills to the next level.
Learn more »
My Pluralsight courses — The topics include Unit Testing, Domain-Driven Design, and more.
Learn more »