Java Spring ExceptionHandler Controller syntax and good practices

I would like to handle my exceptions correctly in Spring, so I have a question about exceptionHandler syntax : Is it ok to throw specific exceptions in the controller, if they are caught by the exception handler ?

More specifically :

Here is the Exception :

public class UnknownUserException extends Exception {

    private static final long serialVersionUID = 1L;

    public UnknownUserException(String message) {
        super(message);
    }
}

Here is the ExceptionHandler with the specific method for UnknownUserException :

@ControllerAdvice
@ResponseBody
public class ControllerExceptionHandler {

    @ExceptionHandler(UnknownUserException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public ErrorMessage unknownUserExceptionMessage(UnknownUserException ex, WebRequest request) {
       ErrorMessage message = new ErrorMessage("The user doesn't exist: " +ex.getLocalizedMessage(), ex);
       return message;
      }
}

Here is one example of a mapping that may raise that exception :

@GetMapping({"/user/{id}"})
    public ResponseEntity<UserProfileDto> getById(@PathVariable Long id) throws UnknownUserException {
            UserProfileDto user = userService.findById(id);
            return ResponseEntity.ok(user);
    }

The userService.findById(id) may throw the UnknownUserException.

From what I understood, the controllerAdvice “overrides” the controller in case of that specific exception thrown by a service, but then, what should I do with my controller ? should I throw the exception again (like above) or catch the specific exception and return a ResponseEntity(HttpStatus.NOT_FOUND) ?

Answer

In an ideal scenario exception should be thrown immediately when it is known in your case as you mentioned service method will throw UnknownUserException that the right thing to do. Your Controller Advice should be able to handle that exception. ContollerAdvice will handle any matching exception that is thrown during execution of the request irrespective of the origin of exception.

Refer to this link for other options on handling exception