简体   繁体   中英

Rest Endpoint Exception Handling

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)));
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM