如何确定在bean验证期间哪个参数导致HttpMessageNotReadableException

对于页码(如果有人输入了“ test”),我想自定义错误消息"Please provide the correct type for the parameter : pageNo"

请求对象:

 {
        "pageSize":6,"pageNo":"test","sortBy": "lastModifiedTime"
    }

如何确定导致异常的参数:

@ExceptionHandler({ HttpMessageNotReadableException.class,HttpMediaTypeNotSupportedException.class,HttpMessageNotWritableException.class,ConversionNotSupportedException.class })
    public ResponseEntity<RestResponse> handleRequestErrors(final Exception ex) {
        RestResponse response = new RestResponse();
        response.setCode(HttpStatus.BAD_REQUEST.value());
        response.setStatus(false);
        response.setMsg(ex.getMessage());
        if (ex instanceof HttpMediaTypeNotSupportedException 
                || ex instanceof HttpMessageNotWritableException
                || ex instanceof HttpMessageNotReadableException) {
            response.setMsgCode(AppCode.E_GEN_CONTENT_TYPE_NOT_SUPPORTED);
        }
        return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
    }

可以对查询参数验证处理相同的场景:

控制器建议:

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public ResponseEntity<RestResponse> handleMethodArgumentTypeMismatchException(HttpServletRequest request,MethodArgumentTypeMismatchException exception) {
        RestResponse response = new RestResponse();
        response.setCode(HttpStatus.BAD_REQUEST.value()); // 400
        response.setStatus(false);
        response.setMsgCode(AppStrings.BAD_REQUEST);
        String param = exception.getName();
        response.setMsg("Please provide the correct type for the parameter : " + param);
        return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
    }

控制器类:

    public ResponseEntity<RestResponse> getNotifications(
                @RequestParam(defaultvalue = "0") @Min(0) IntegerpageNo,@RequestParam(defaultvalue = "5") @Min(1) Integer pageSize,@RequestParam(defaultvalue = "lastModifiedTime") String sortBy) {
shenghuat 回答:如何确定在bean验证期间哪个参数导致HttpMessageNotReadableException

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3124059.html

大家都在问