Tarta
Tarta

Reputation: 2063

Can ResponseEntity be used outside of Controllers in Spring?

I have the following question. I find myself in using ResponseEntity inside a RestController in Spring whenever I want to manipulate the HTTP response coming back from my controller.

Let's say now that the outcome of this response depends indeed on what happens on the business layer below. Let's say this layer makes an http call, if it goes right I forward back above a positive message, instead I forward a negative message.

My controller now receives a message, but it would be nice to analyze whetever what happened down below was successful or not. So, can I return from the business level a ResponseEntity and mark it already as 400 or 200 (depending on what happens down there) or there is another better practice?

Upvotes: 0

Views: 842

Answers (2)

Piotr Podraza
Piotr Podraza

Reputation: 2029

Sure you can. Technically ResponseEntity is a class like any other, you can return an instance of it from any layer.

The question you should ask yourself though, is this a good practise to return object of that class from a method that suppose to perform some business logic? For me it does not feel right. You introduce layers to separate concerns. Your domain layer should be totally agnostic of off communication protocol your application offer.

If you design domain layer right you'll know what went wrong based on thrown exception. Then you'll also know which HTTP status you should return.

Upvotes: 3

This violates the concept of separation of layers: It is the controller's only job, and only the controller's job, to translate between the language of HTTP and your application's internal language (API). What if, in the future, you want to change how your HTTP API works but support multiple versions at the same time?

Instead, this is exactly what exceptions are for: Throw a sensible exception from your business methods. I frequently create subclasses of exception types such as IllegalStateException to represent application-specific errors, and sometimes I use the existing exception classes directly.

Upvotes: 2

Related Questions