0

I'd like to do custom exception handling for a REST API.

This is the code I have.

Controller Endpoint

@PatchMapping(value="/customer/name", produces = "application/json") public ResponseEntity<Customer> updateName( @RequestParam(value="customerId") Long customerId, @RequestParam(value="name") String name){ customerRepository.updateCustomerName(customerId, name); Customer updatedCustomer = customerRepository.findCustomer(customerId); return new ResponseEntity<Customer>(updatedCustomer, HttpStatus.OK); } 

Custom Exception Handling Class

@ControllerAdvice public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler{ @ExceptionHandler(value = {Exception.class}) public ResponseEntity<Object> handleAll(Exception ex, WebRequest request) { return new ResponseEntity<>( ex, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } 

If I force an error inside the endpoint method (such as adding the null pointer exception below), it will correctly enter the handleAll method and return the custom error.

String x = null; int y = x.length(); 

But, if instead of that, I generate the error by going to Postman and pass a String instead of a Long in the customerId parameter, it doesn't enter the custom error class.

In fact, it never enters the controller method.

How to make the custom error class catch and display custom error for that as well?

thanks

2
  • try to override method handleMethodArgumentNotValid it should work Commented Feb 17, 2021 at 22:23
  • @bilak tried. Didn't work. Still doesn't enter the handleMethodArgumentNotValid method. Commented Feb 18, 2021 at 13:59

1 Answer 1

1

try to override handleMethodArgumentTypeMismatch

@ExceptionHandler({MethodArgumentTypeMismatchException.class}) public ResponseEntity<Object> handleMethodArgumentTypeMismatch( MethodArgumentTypeMismatchException ex, WebRequest request) { return ResponseEntity } 
Sign up to request clarification or add additional context in comments.

4 Comments

try to override handleMethodArgumentTypeMismatch ``` @ExceptionHandler({MethodArgumentTypeMismatchException.class}) public ResponseEntity<Object> handleMethodArgumentTypeMismatch( MethodArgumentTypeMismatchException ex, WebRequest request) { return ResponseEntity } ```
Perfect! With MethodArgumentTypeMismatchException it worked. Thank you. It needs to be with no @Override. Please add this answer as a new answer here and I'll check it as answer accepted. Just don't want to do that here because the first answer didn't work.
I changed the answer :)
Done. Thanks for your help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.