spring-boot-starter-validation 中主要有以下几种异常:

  1. ConstraintViolationException:违反约束条件的异常,例如参数校验失败。
  2. MethodArgumentNotValidException:方法参数校验异常。
  3. BindException:数据绑定异常。
  4. HttpMessageNotReadableException:请求消息不可读异常。

错误处理可以通过 @ExceptionHandler 注解实现,例如:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ResponseEntity.badRequest().body(errorMsg);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException ex) {
        String errorMsg = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        return ResponseEntity.badRequest().body(errorMsg);
    }

    // 其他异常处理方法

}

在上面的代码中,我们使用 @RestControllerAdvice 注解来定义一个全局异常处理器,然后在方法上使用 @ExceptionHandler 注解来指定要处理的异常类型。在方法中,我们可以根据具体的异常类型来处理异常,并返回相应的错误信息。在这个例子中,我们处理了 MethodArgumentNotValidException 和 ConstraintViolationException 两种异常。

spring-boot-starter-validation 中有几种异常错误处理怎么写

原文地址: https://www.cveoy.top/t/topic/bqfb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录