3

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?

1
  • Have you tried to overload the method? Create a new method (use what you showed above) and change the @PathVariable from a Long to a String in the new method. Commented Mar 3, 2021 at 21:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm I'm not reaching my ControllerAdvice with MethodArgumentTypeMismatchException... Why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.