@GetMapping("/users/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { Optional<User> user = userService.findById(id); if (user.isPresent()) { return ResponseEntity.ok(user.get()); } else { throw new UserNotFoundException("User not found"); } }
Throwing UserNotFoundException typically leads to a 404 response if there is a handler mapping this exception to 404. Otherwise, it might cause a 500 error. In well-designed apps, this exception is mapped to 404.
Option D correctly returns a ResponseEntity with the message and status. Option D returns a String but lacks @ResponseBody, so it returns a view name. Option D has a void return but tries to return a String, causing a syntax error. Option D returns ResponseEntity inside a String method, which is invalid.
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public String handleAllExceptions(Exception ex) { return "Error occurred"; } }
The global handler catches all exceptions of type Exception and returns 500. Since it is generic, it prevents more specific handlers from running. UserNotFoundException extends Exception, so it is caught here first.
@ExceptionHandler(UserNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody public Map<String, String> handleUserNotFound(UserNotFoundException ex) { Map<String, String> error = new HashMap<>(); error.put("error", ex.getMessage()); return error; }
The method returns a Map with a key "error" and the exception message. Spring converts this Map to JSON, so the client receives a JSON object with the error message.
Annotating a custom exception with @ResponseStatus lets Spring Boot automatically set the HTTP status when the exception is thrown, without needing explicit handlers. This keeps code cleaner and easier to maintain.