简体   繁体   English

休息端点异常处理

[英]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.我使用 Long 作为userId 的数据类型,它在通过如下所示的邮递员调用端点时工作正常,并且我能够显式处理异常。

localhost:8080/order-service/save-order/1本地主机: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本地主机:8080/order-service/save-order/abc

the spring boot implicitly handles the exception and give 400 bad request. spring boot 隐式处理异常并给出 400 个错误请求。

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.我想要的是在参数的变量类型不等于 long 时抛出自定义错误消息,例如“请发送正确的 userId”。

@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您可以实现自己的自定义验证器,请参见此处: 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.如果输入合适,则返回 true,如果不合适,则返回 false,您还可以在那里定义要在用户输入错误输入时向用户显示的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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