简体   繁体   中英

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.

@RestControllerAdvice
public class ExceptionCatcher {

    @ExceptionHandler(NumberFormatException.class)
    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

You need to validate the inputs using @Validated annotations. Please follow below link for more details: https://howtodoinjava.com/spring-rest/request-body-parameter-validation/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM