I have a question regarding validations and exceptions in DDD.
I have a ValueObject say, PasswordText
which takes a string argument in it's constructor. Checks if the string matches the password criteria. If criteria, matches then the new object is initialized otherwise it throws an exception (DomainException
).
The problem with this approach is, now, there could be many exceptions lying around in the Domain models that are ready to explode. It will be a headache for consumers of my Domain models to catch appropriate exceptions and act accordingly (like sending correct HTTP Status Code or something like that.)
My first question is how can I make this easy on them? Do I need to change my approach like using Notification Pattern or Either Pattern making it explicit for my consumers that this could return an error?
If the answer to above question is yes then how can I implement this approach for constructors? If answer of this question is Factories then sadly I have to create Factory for each domain model just for the sake of returning errors!
Also, I would like to add that the problem with Notification/Either Pattern is that, now my application code will be mixed with error handling code. How one should deal with this?
Is there any better way altogether for validations? Or How would you go about it?
Either/Maybe
at every domain call, or burden the client with wrapping calls intry/catch
(or a single top-level handler). The latter is preferable in most systems (you would certainly know if you are working within a system that prefers the former). Many web frameworks already work by using a top-leveltry/catch
to convert errors into HTTP messages/error pages.