Q:

Exception Handling in Spring boot

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?

A:

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.

