3

I have a spring-boot application which has the following end point:

@RequestMapping("/my-end-point")
public MyCustomObject handleProduct(
  @RequestParam(name = "productId") String productId,
  @RequestParam(name = "maxVersions", defaultValue = "1") int maxVersions,
){
   // my code
}

This should handle requests of the form

/my-end-point?productId=xyz123&maxVersions=4

However, when I specify maxVersions=3.5, this throws NumberFormatException (for obvious reason). How can I gracefully handle this NumberFormatException and return an error message?

Nik
  • 5,515
  • 14
  • 49
  • 75

1 Answers1

14

You can define an ExceptionHandler in the same controller or in a ControllerAdvice that handles the MethodArgumentTypeMismatchException exception:

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public void handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
    String name = ex.getName();
    String type = ex.getRequiredType().getSimpleName();
    Object value = ex.getValue();
    String message = String.format("'%s' should be a valid '%s' and '%s' isn't", 
                                   name, type, value);

    System.out.println(message);
    // Do the graceful handling
}

If during controller method argument resolution, Spring detects a type mismatch between the method argument type and actual value type, it would raise an MethodArgumentTypeMismatchException. For more details on how to define an ExceptionHandler, you can consult the documentation.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151