I'm trying to find the best solution to abstract the return type of the service layer.

I have a controller that calls a service to create a user. The service calls a REST API and receives an HTTP status code (201, 400, 409 ...). I don't want to return the HTTP code to the controller to keep the application loosely coupled (actually we use a REST API, maybe later GraphQL, maybe gRPC ...) Otherwise, I will need to change my controller code every time I change the service layer code.

The reflection I get is to make custom exceptions and throw an exception depending on the HTTP status:

if 409 Throw an exception the user account already exists.
if 400 Throw an exception bad request arguments.
else 201 return true without throwing an exception.

I have doubts about having dozens of exceptions to make in my application depending on each service method/function context/scope(user, article, product...).

1 Answer 1


Defining a lot of different classes (or at least values) for different outcomes is the price of decoupling. Since you only have to write the adapter code once, but can reuse it in business code as long as you want, this is still a worthwhile thing to do.

The question to ask here is whether your business code really does need to handle all 63 status codes individually or whether it really does only one of e.g. four different things depending on the return code. If that is the case, your adapter code simultaneously serves to decouple policy from mechanism (good thing 1) and to simplify the error logic (good thing 2).

If it should turn out that you do need to handle all the different status individually, you should ask why that is so. Is your service perhaps secretly a web server and doesn't know it yet? Or do you have stringent logging requirements that require you to retain all detail of all interactions?

In such cases, maybe you should pass HTTP status codes after all. Even if you do switch technologies later it's not that hard to change your adapter so that it pretends to receive HTTP status codes rather than e.g. Query Language error conditions, and very likely it won't have to simulate all 63 of them either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.