脚手架搭建(七)参数校验及全局异常捕捉

一、引入依赖

在frame-basic子模块中引入依赖,修改pom.xml文件

二、自定义异常类

创建CustomException.java异常类,在后续义务开发中,所有一直的异常都将会用这个异常类进行抛出

@Data
public class CustomException extends RuntimeException{
    
    private String code;

    /**
     * Constructs a new runtime exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public CustomException(String message) {
        super(message);
        this.code = ResultCodeEnum.ERROR.getCode();
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param message the detail message. The detail message is saved for
     *                later retrieval by the {@link #getMessage()} method.
     */
    public CustomException(String code, String message) {
        super(message);
        this.code = code;
    }

    /**
     * Constructs a new runtime exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * {@code cause} is <i>not</i> automatically incorporated in
     * this runtime exception's detail message.
     *
     * @param message the detail message (which is saved for later retrieval
     *                by the {@link #getMessage()} method).
     * @param cause   the cause (which is saved for later retrieval by the
     *                {@link #getCause()} method).  (A {@code null} value is
     *                permitted, and indicates that the cause is nonexistent or
     *                unknown.)
     * @since 1.4
     */
    public CustomException(String message, Throwable cause, String code) {
        super(message, cause);
        this.code = code;
    }

    /**
     * Constructs a new runtime exception with the specified cause and a
     * detail message of {@code (cause==null ? null : cause.toString())}
     * (which typically contains the class and detail message of
     * {@code cause}).  This constructor is useful for runtime exceptions
     * that are little more than wrappers for other throwables.
     *
     * @param cause the cause (which is saved for later retrieval by the
     *              {@link #getCause()} method).  (A {@code null} value is
     *              permitted, and indicates that the cause is nonexistent or
     *              unknown.)
     * @since 1.4
     */
    public CustomException(Throwable cause, String code) {
        super(cause);
        this.code = code;
    }

    /**
     * Constructs a new runtime exception with the specified detail
     * message, cause, suppression enabled or disabled, and writable
     * stack trace enabled or disabled.
     *
     * @param message            the detail message.
     * @param cause              the cause.  (A {@code null} value is permitted,
     *                           and indicates that the cause is nonexistent or unknown.)
     * @param enableSuppression  whether or not suppression is enabled
     *                           or disabled
     * @param writableStackTrace whether or not the stack trace should
     *                           be writable
     * @since 1.7
     */
    public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, String code) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.code = code;
    }
}

三、参数校验及异常处理

参数校验注解

  • @NotNull:参数不能为null
  • @NotBlank:参数不能为null、空字符串、空白字符串
  • @Length:限制参数长度在一定范围
  • @Email:限制参数为邮箱格式

全局异常捕捉处理

1、@ControllerAdvice和@RestControllerAdvice区别

这两个注解的区别其实跟@Controller,@RestController的区别类似。就是如果方法需要返回json数据时,@RestControllerAdvice不用额外添加@ResponseBody注解

2、异常处理
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public JsonResult<Void> handleCustomException(CustomException e) {
        log.error("自定义异常", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public JsonResult<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("参数校验异常", e);
        return ResultUtils.error(ResultCodeEnum.REQUEST_PARAM_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常", e);
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        return ResultUtils.error(ResultCodeEnum.REQUEST_PARAM_ERROR.getCode(), fieldErrors.get(0).getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> bindExceptionHandler(BindException e) {
        log.error("参数校验异常", e);
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        return ResultUtils.error(ResultCodeEnum.REQUEST_PARAM_ERROR.getCode(), fieldErrors.get(0).getDefaultMessage());
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public JsonResult<Void> bindHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        log.error("请求方式不支持");
        return ResultUtils.error(ResultCodeEnum.REQUEST_METHOD_ERROR);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值