Why Spring MVC does not allow to expose Model or BindingResult to an @ExceptionHandler?

后端 未结 6 1092
时光说笑
时光说笑 2021-02-12 18:41

Situation

I\'m trying to group the code that logs the exceptions and render a nice view in a few methods. At the moment the logic is sometime in the @RequestHand

6条回答
  •  情歌与酒
    2021-02-12 19:02

    To improve the first answer:

        @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public VndErrors methodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) {
        List fieldErrors = ex.getBindingResult().getFieldErrors();
        List globalErrors = ex.getBindingResult().getGlobalErrors();
        List errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
        VndError error;
        for (FieldError fieldError : fieldErrors) {
            error = new VndError(ErrorType.FORM_VALIDATION_ERROR.toString(), fieldError.getField() + ", "
                    + fieldError.getDefaultMessage());
            errors.add(error);
        }
        for (ObjectError objectError : globalErrors) {
            error = new VndError(ErrorType.FORM_VALIDATION_ERROR.toString(),  objectError.getDefaultMessage());
            errors.add(error);
        }
        return new VndErrors(errors);
    }
    

    There is already MethodArgumentNotValidException has already a BindingResult object, and you can use it, if you don't need to create an specific exception for this purpose.

提交回复
热议问题