Code convention says no logic in the controllers. All should be handled in the service layer. My question is especially about returning ResponseEntity.
Should it be handled in RestController or in Service layer?
I tried both ways. I think RestController is the suitable place to return ResponseEntity. Because we are using mappings in the RestController.
On the other hand, we know the controllers should not include any logic.
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
or
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return employeeService.findEmployeeById(id);
}
ControllerAdvice for exception handling is my another concern. Which way is the best to use?
Thanks for your advance.
@RestController Annotation: RestController is used for making restful web services with the help of the @RestController annotation. This annotation is used at the class level and allows the class to handle the requests made by the client.
Status Code, Response Body, Headers are one of the core parts for REST
The controller should be concerned with accepting the request, asking the correct domain service to process the request, and handing off the response to the correct place.
It's right that controllers should not perform all business logic here but sending the HTTP response should be done in Controller instead of service.
Although Status code can be sent using @ResponseStatus(HttpStatus.XXX)
which might not be helpful for in scenarios where we have to send Status Code according to the conditions. You can create custom ResponseDTO which generally have body, message and status code.
public ResponseEntity<ResponseDTO> method() {
return new ResponseEntity<ResponseDTO>(response,response.getStatus());
}
Code convention says no logic in the controllers.
Not really. Code convention says each layer has to perform itself logic which it is responsible of.
Computing the result, retrieving data requested/needed by the request is clearly not the rest controller job but sending an http response, what returning ResponseEntity
does is its job. So this looks the correct way :
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
If the ResponseEntity
was produced by your service, your service would be coupled with the Http layer. Not desirable and make it less reusable as a service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With