Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot how to return custom error message when validating @PathVariable parameters

Is it possible to add some custom validation message to path variable?

I have some GET

  @GetMapping("/v2/tw/{id}")
    public TwDto getTw(Authentication auth, @PathVariable Long id) {

In case of /v2/tw/someString I'd like to catch error and add some custom error message like "invalid tw ID"... How to do that? In ControllerAdvice add some ExceptionHandler?

like image 710
Matley Avatar asked Jan 28 '26 07:01

Matley


1 Answers

For your particular use case, you can use @ExceptionHandler in the Controller or in a @ControllerAdvice class as shown here. For example, I am returning NOT_FOUND error for the sake of it.

@ExceptionHandler({MethodArgumentTypeMismatchException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "this is the reason")
public void handle() {
}

You may not see the reason in the actual error response, until you enable

server:
  error:
    include-message: always

If you think your @ExceptionHandler is only needed in a Controller class you can keep the method inside the controller. Alternatively you can create a @ControllerAdvice class and put the method there, so that you can reuse across multiple controllers in your application.


However, if you want a more complex validation, I will suggest to keep the id type to String and then cast manually into Long and perform the validation. Doing so you can throw your own RuntimeException and handle different cases.

like image 76
Amit Phaltankar Avatar answered Jan 29 '26 21:01

Amit Phaltankar



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!