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