How to avoid NumberFormatException in Spring boot API

I have a Spring boot Get API which returns a ‘User’ object for a given user id.

@GetMapping( path = "/users/{userId}")
public ResponseEntity<User> getUser(
        @PathVariable( userId )
                Long id) throws CustomException {
      //retuen user object

When someone passes a string value to the endpoint as userId this returns ‘NumberFormatException’. Which gives an idea of the type of userId that is used on the side of the system. Is there a possibility that I can return a CustomException rather than returning a ‘NumberFormatException’.

One option is to use type String for userId and then try to convert it to Long inside the method. Other than that, Is there a better way to address this issue with any inbuild finalities of Spring Boot?


Yes you can by creating an exception advice class that can handle the runtime exceptions.

For example to handle the exceptions you must do the following:-

1- Create a custom class to use it as an exception response class.

public class ExceptionResponse {

    private String message;

    public ExceptionResponse(String message) {
        this.message = message;

    public String getMessage() {
        return message;

    public void setMessage(String message) {
        this.message = message;

2- create an exception handler class to handle the thrown exceptions and add the exceptions that you want to handle.

public class ExceptionCatcher {

    public ResponseEntity<ExceptionResponse> numberFormatExceptionHandler(NumberFormatException exception) {
        ExceptionResponse response = new ExceptionResponse(exception.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);

Or you can check this link to get more informations spring-rest-error-handling-example