Search code examples
javaspringhttpresponsedto

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?


Solution

  • 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.