Rest Endpoint Exception Handling

dasitha :

Below is my rest endpoint. I used Long for data type for userId, Its working fine when calling the endpoint via postmen like below and I am able to handle exceptions explicitly.

localhost:8080/order-service/save-order/1

but when I am calling like this with a string type parameter,

localhost:8080/order-service/save-order/abc

the spring boot implicitly handles the exception and give 400 bad request.

what I want is to throw a custom error message like "please send proper userId" when the variable type of parameter not equal to long.

@PostMapping(path = "/save-order/{userId}")
    @ResponseBody
    public ResponseEntity<ExceptionResponse> addOrder(@Valid @RequestBody 
         OrderDTO orderDto, @Valid @PathVariable(name = "userId") Long userId) throws BatchException, UserExceptions, BatchIdException, InvalidDateFormatException, DeliveryIdException,BatchMerchantException {
        return ResponseEntity.ok(new ExceptionResponse("Order Saved", 201, orderServiceImpl.saveOrder(orderDto, userId)));
    }
Max R. :

You can implement your own custom validator, see here: https://www.baeldung.com/spring-mvc-custom-validator

Return true if the input fits and false if not, you can also define the message there you want to show the user if he enters a wrong input.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156129&siteId=1