I use validator in my spring boot, but can not catch any exception, my code is like that
first I create a bean with annotation
@Data
@EqualsAndHashCode(callSuper = false)
public class OrderDetailPO extends BaseEntity<String>{
private static final long serialVersionUID = 1L;
@NotNull
@Size(max=32,message="ordercode is null")
private String orderCode;
@NotBlank
@Size(max=32,message="productMode is null")
private String productMode;
@NotBlank
@Size(max=128,message="hotelType is null")
private String hotelType;
@NotBlank
@Size(max=32,message="goodsId is null")
private String goodsId;
}
then I use @validated in the controller
public Result<?> createOrderDetail( @RequestBody @Validated OrderDetailPO orderDetail,BindingResult bindingResult) throws ParseException, UnsupportedEncodingException {
// if (bindingResult.hasErrors()) {
// String errMsg="";
// for(FieldError err: bindingResult.getFieldErrors()) {
// errMsg += err.getField()+" is " + err.getCode();
// }
// return Result.buildFail(errMsg);
// }
then I use an empty request send to the controller, but nothing happens... In my opinion, I can see the error in bindingResult, but I can not catch an exception as MethodArgumentNotValidException even if I delete bindingResult , and how can I let the exception appear?
yeah, if I only have param not requestbody, how to throw exception? for example
public Result<?> orderDetailSelByAccountId( @NotBlank @Size(min=10,max=32)@PathVariable(value="accountId") String accountId) {
}
If you use @Valid
annotation on your OrderDetailPO
you have some options to handle an invalid request.
Option 1:
You use BindingResult
in your method signature like you did in your code. Now you are able to use if (bindingResult.hasErrors())
and if it is true you are free to do anything you want. You can throw your own exceptions, return a custom message or just go on with your code. Thats your decision. And you don't have to catch any exception.
Option 2:
Delete BindingResult
in your method signature. This means that Spring will automatically return a BadRequest
to the client. It will respond with an org.springframework.web.bind.MethodArgumentNotValidException
with all the information about the invalid request. In this case you will not enter your method. Same as option 1, no exception must be caught.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With