I sometimes receive similar questions from different people, which is always a sign that the topic in question is interesting and worth writing about. But I have never received the same question from three (3!) people within the span of one or two weeks. Here’s this question:
How can I go about responding with different HTTP status codes depending on the nature of the failure without API (UI) logic leaking into the domain layer? In particular, how can I differentiate between a
Resultthat failed because of a validation error and another one that failed because the entity was not found? I’d like to respond with a
400on the first type of error and with a
404on the second.
And here’s my response: Advanced error handling techniques. The main points are:
Create an explicit
Resultin combination with that class instead of strings.
Resultinto HTTP response codes in
I will probably make a small series or even a Pluralsight course, this subject is quite topical.
It’s especially unclear how to combine ASP.NET validation attributes with Value Objects. On the one hand, Value Objects is where all domain knowledge should reside. But on the other, ASP.NET validation attributes are a nice and handy mechanism for setting up validation rules directly in the DTO data contracts. This is something my team and I implemented at my recent project and I want to show how we did that.
By the way, if you want to send me a question, hit reply. I’m curious to see what topics of interest or pain points you have. I promise that I’ll read every message personally, and will also respond.