Springboot 自定义全局异常处理

业务异常

在项目根包目录下新建 exception.base 包
新建BaseException 继承 RuntimeException

package com.ddz.errordemo.handler;

/**
 * 基础异常类
 * @author Lenovo
 * @date 2022/4/26
 */
public class BaseException extends RuntimeException {
    /**
     * 所属模块
     */
    private String module;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误码对应的参数
     */
    private Object[] args;

    /**
     * 错误消息
     */
    private String defaultMessage;

    public BaseException(String module, String code, Object[] args, String defaultMessage) {
        this.module = module;
        this.code = code;
        this.args = args;
        this.defaultMessage = defaultMessage;
    }

    public BaseException(String module, String code, Object[] args) {
        this(module, code, args, null);
    }

    public BaseException(String module, String defaultMessage) {
        this(module, null, null, defaultMessage);
    }

    public BaseException(String code, Object[] args) {
        this(null, code, args, null);
    }

    public BaseException(String defaultMessage) {
        this(null, null, null, defaultMessage);
    }

    public String getModule() {
        return module;
    }

    public void setModule(String module) {
        this.module = module;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Object[] getArgs() {
        return args;
    }

    public void setArgs(Object[] args) {
        this.args = args;
    }

    public String getDefaultMessage() {
        return defaultMessage;
    }

    public void setDefaultMessage(String defaultMessage) {
        this.defaultMessage = defaultMessage;
    }
}

根据自己的需要新建业务异常类

package com.ddz.errordemo.exception;

import com.ddz.errordemo.exception.base.BaseException;

/**
 * 用户信息异常类
 */
public class UserException extends BaseException
{
    private static final long serialVersionUID = 1L;

    public UserException(String code, Object[] args)
    {
        super("user", code, args, null);
    }
}

在项目根包目录下新建 exception.handler包;
新建RestExceptionHandler 异常处理类

package com.ddz.errordemo.exception.handler;

import com.ddz.errordemo.exception.base.BaseException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Lenovo
 * @date 2022/4/26
 */
@RestControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Object exception(HttpServletRequest request, Exception e) {
        return request.getRequestURL() + "全局异常" + e.getMessage();
    }

    @ExceptionHandler(NullPointerException.class)
    public Object nullException(Exception e) {
        return "空指针" + e.getMessage();
    }

    @ExceptionHandler(RuntimeException.class)
    public Object busException(BaseException e) {
        return "模块" + e.getModule() + "异常码:" + e.getCode() + "异常信息:" + e.getMessage();
    }
}

捕捉validation框架校验异常

如果springboot 版本高于3.5.1 需要导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

在异常类中添加方法

import com.ddz.project.common.exception.code.BusinessException;
import com.ddz.project.common.exception.code.BaseResponseCode;
import com.ddz.project.common.exception.code.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
/**
 * RestExceptionHandler
 *
 * @author Lenovo
 * @version V1.0
 * @date 2020年3月18日
 */
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {

    /**
     * 自定义全局异常处理
     */
    @ExceptionHandler(value = BusinessException.class)
    Object businessExceptionHandler(BusinessException e) {
        log.error("BusinessException:{}", e.getMessageCode(), e);
        return e.getMessageCode()+e.getDetailMessage();
    }


    /**
     * 处理validation 框架异常, 需要controller添加@Validated注解
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    Object methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        // String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return errors.get(0).getDefaultMessage();
    }

    /**
     * 校验List<entity>类型, 需要controller添加@Validated注解
     * 处理Validated List<entity> 异常
     */
    @ExceptionHandler
    public Object handle(ConstraintViolationException exception) {
        log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", exception, exception);
        Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations) {
            builder.append(violation.getMessage());
            break;
        }
        return builder.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LOVE_DDZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值