0

In my project, I have a service layer that manipulates repositories. The service layer is called by my controllers.

In many cases, my controller layer is able to validate incoming information before it gets any further into the system. In some cases however, errors may arise due to submitted data not being valid, but only at a point that is within my service layer.

With that in mind, let's assume I'm doing a user signup flow:

  • Duplicate usernames are not allowed
  • The username can be provided
    • If the username is not provided, it is generated from the first and last name

This means that the process of generating (if necessary) and checking for duplicate usernames transpires in the service layer.

In the event of a duplicate, what is the most decoupled and ideal way for me to signal back to the caller (be it a controller, a background task, or even another service) - that:

  • There is a problem with the username field
  • Where applicable, the username that was generated

Ideally the approach suggested would be able to apply to errors that happen in other services so that I can come up with a consistent way to report and thus handle errors in calling layers.

Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112

2 Answers2

2

What I typically do is, have the business/domain/application layer all throw regular .NET exceptions (keeping the stack trace!), which contains the information about what the exception is about.

In the service layer a global exception handler then transforms the exception to a fault (in the case of a WCF service). It can also log the internals at that time.

So the internals (the exception) are kept internally; but the public part of it is automatically exposed to the consumers of your service.

Typically I use FluentValidation to do the validation in the application and business layers, which allows you to put validations in specific validation classes and also reuse them.

L-Four
  • 13,345
  • 9
  • 65
  • 109
1

I like @L-Three's answer, but I'd like to offer an alternative suggestion: Make validation errors part of the return result from your service layer methods.

My feeling is that domain/service layers should be responsible for ALL validation, and that any input validation done in a UI is nice-to-have.

Chris McKenzie
  • 3,681
  • 3
  • 27
  • 36