1

From the earlier post mentioned here it is clear that Controller layer is responsible for returning Http response. However code example mentioned there still needs some logic to return which type of Http response. If in the service layer - employeeService.findEmployeeById(id) returns null then the controller needs a logic to decide what type of Http status to be returned.

There could be many if-else condition based on status of emp. How best to avoid logic in Controller

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
   Employee emp = employeeService.findEmployeeById(id);
   if(emp != null)
        return ResponseEntity.status(HttpStatus.OK).body(emp);
   return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
user14132461
  • 73
  • 1
  • 6
  • can you explain with some example on this statement? `There could be many if-else condition based on status of emp`, and according to me emp status should not define status code – Ryuzaki L Nov 29 '20 at 19:12
  • My bad, findEmployeeById is not good example. Better way to restate is, if while doing business logic in service layer there are exceptions thrown or there will be some logic to decide what Http code to be returned. I will edit my question with further research. I liked the reasoning of @Jalil.Jarjanazy – user14132461 Nov 30 '20 at 05:48

1 Answers1

1

First of all, the ResponseEntity.status(HttpStatus.NOT_FOUND) isn't suitable for the case of an employee not being found. It's used when the user sends a request to an endpoint that has no controller to handle.

As for the case of what to return if the employee wasn't found, it's really a design choice. You can send a BAD_REQUEST in which you put some kind of a message to tell the client that the employee wasn't found

ResponseEntity.status(HttpStatus.BAD_REQUEST).body(String.format("%s employee wasn't found", id))

Or, you can simply return a 200 with an empty body. As for the extra condition statements (if, else). Well, you have to write those.

Jalil.Jarjanazy
  • 839
  • 1
  • 9
  • 22
  • I liked (if, else) section must.))) – Shant Khayalian Nov 29 '20 at 22:17
  • @Jalil.Jarajanazy as per the documentation status 404 describes "The server has not found anything matching the Request-URI. " As per this when client access the URL say http://localhost:8080/api/employees/1234 and if that id 1234 is not in the DB then shouldn't the Server throw 404 ? – user14132461 Nov 30 '20 at 15:40
  • @user14132461 Yes you are right. This answer is a good one. https://stackoverflow.com/questions/26845631/is-it-correct-to-return-404-when-a-rest-resource-is-not-found – Jalil.Jarjanazy Nov 30 '20 at 17:00
  • Not true. https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html "404 status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable." – Panagiotis Sakellariou Feb 20 '23 at 10:38