Reputation: 779
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
Upvotes: 0
Views: 1305
Reputation: 103
try to override handleMethodArgumentTypeMismatch
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
public ResponseEntity<Object> handleMethodArgumentTypeMismatch( MethodArgumentTypeMismatchException ex, WebRequest request) {
return ResponseEntity
}
Upvotes: 1