I have a project implemented by Onion Architecture, and it is similar to Ordering. I need to handle validation errors in the all layers. As far as I know, there are generally two following approaches to do handle the errors:
1- Throwing exception
2- Returning Operation Result
In your view, which one is the best?
1- Throwing exception
This is my approach. As you can see in ValidatorBehavior, I have used ValidatorBehavior
to handle validation errors related to validate my commands like this. FluentValidation is used to validate input command and errors are cached in Handle
method in ValidatorBehavior
.
One of the issues is FluentValidation
throw exception if command isn't valid. This exception could be cached in HttpGlobalExceptionFilter in the web API.
Some people said exception is for unexpected case, but in this scenario (Validation), we know the result of validation phase and we implemented some business rules by throw exception.
Another one is using throwing exception in Domain Layer
like StatusChangeException. So there is no doubt, we need throwing exception in other layers.
2- Returning Operation Result
In the second approach suggested by some of my friends, we can use handle errors for showing these errors to end users by an object named OperationResult
. In performance viewpoint, it seems to be better because throwing exceptions is more expensive than first approach.
What do you think about these two approach? I am wondering if you share your idea to make the best decision.