Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
Nik Avatar asked Apr 08 '26 20:04

Nik


1 Answers

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.

like image 146
Ali Dehghani Avatar answered Apr 10 '26 10:04

Ali Dehghani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!