其他分享
首页 > 其他分享> > SpringBoot全局异常处理及自定义异常

SpringBoot全局异常处理及自定义异常

作者:互联网

首先定义自定义返回类,如果自己项目中已经有了自定义返回类只需要将后面的代码做相应的修改即可;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 统一API对象返回
 * @param <T>
 * @Author: TanXJ
 * @Date: 2021/10/13 9:31
 */
@Data
@NoArgsConstructor
public class ResultBean<T> {
    /** 状态码 */
    @ApiModelProperty(value = "状态码", example = "200")
    private Integer code;

    /** 返回消息 */
    @ApiModelProperty(value = "返回消息", example = "操作成功")
    private String message;

    /** 状态 */
    @ApiModelProperty(value = "状态", example = "true")
    private boolean status;

    /** 返回数据 */
    @ApiModelProperty(value = "返回数据", example = "")
    private T data;

    public ResultBean(Integer code, String message, boolean status, T data) {
        this.code = code;
        this.message = message;
        this.status = status;
        this.data = data;
    }

    public ResultBean(ResultCode resultCode, boolean status, T data) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMsg();
        this.status = status;
        this.data = data;
    }

    public ResultBean(ResultCode resultCode, boolean status) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMsg();
        this.status = status;
        this.data = null;
    }

    public static <T> ResultBean success() {
        return new ResultBean<>(ResultCode.OK, true);
    }

    public static <T> ResultBean message(String message) {
        return new ResultBean<>(ResultCode.OK.getCode(), message, true, null);
    }

    public static <T> ResultBean success(T data) {
        return new ResultBean<>(ResultCode.OK, true, data);
    }

    public static <T> ResultBean fail() {
        return new ResultBean<>(ResultCode.ERROR, false);
    }

    public static <T> ResultBean fail(ResultCode resultCode) {
        return new ResultBean<>(resultCode, false);
    }

    public static <T> ResultBean fail(Integer code, String message) {
        return new ResultBean<>(code, message, false, null);
    }

    public static <T> ResultBean fail(ResultCode resultCode, T data) {
        return new ResultBean<>(resultCode, false, data);
    }

    public static <T> ResultBean fail(Integer code, String message, T data) {
        return new ResultBean<>(code, message, false, data);
    }

}

创建全局异常处理

import com.newmap.common.response.ResultBean;
import com.newmap.common.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常处理
 * @Author: TanXJ
 * @Date: 2022/5/28 19:14
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public ResultBean bizExceptionHandler(HttpServletRequest req, CustomException e){
        log.error("发生业务异常!原因是:{}",e.getMessage());
        return ResultBean.fail(e.getCode(),e.getMessage());
    }

    /**
     * 处理运行时异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public ResultBean runtimeExceptionHandler(HttpServletRequest req, RuntimeException e){
        log.error("发生运行时异常!原因是:{}",e.getMessage());
        return ResultBean.fail(500, e.getMessage());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultBean exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常!原因是:",e);
        return ResultBean.fail(ResultCode.SYSTEM_ERROR);
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBean exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常!原因是:",e);
        return ResultBean.fail(ResultCode.UNKNOWN_ERROR);
    }
}

创建自定义异常处理类,这里只定义了一个自定义异常处理类,在实际的的项目中可以定义多个自定义异常处理类

import com.newmap.common.response.ResultCode;
import lombok.Getter;

/**
 * @ClassName: StudentException
 * @Description: 自定义异常类
 * @Author: TanXJ
 * @Date: 2022/5/28 19:09
 */
@Getter
public class CustomException extends RuntimeException {
    private Integer code;
    private String msg;

    public CustomException() {
        super();
    }

    public CustomException(ResultCode resultCode) {
        super(resultCode.getMsg());
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }

    public CustomException(ResultCode resultCode, Throwable cause) {
        super(resultCode.getMsg(), cause);
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }

    public CustomException(String errorMsg) {
        super(errorMsg);
        this.msg = errorMsg;
    }

    public CustomException(Integer errorCode, String errorMsg) {
        super(errorMsg);
        this.code = errorCode;
        this.msg = errorMsg;
    }

    public CustomException(Integer errorCode, String errorMsg, Throwable cause) {
        super(errorMsg, cause);
        this.code = errorCode;
        this.msg = errorMsg;
    }
    public Integer getErrorCode() {
        return code;
    }

    public void setErrorCode(Integer errorCode) {
        this.code = errorCode;
    }

    public String getErrorMsg() {
        return msg;
    }

    public void setErrorMsg(String errorMsg) {
        this.msg = errorMsg;
    }

    public String getMessage() {
        return msg;
    }

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }
}

代码中应用

@Override
    public UserPO add(HttpServletRequest httpServletRequest, UserVO userVO) {
        // 检查用户信息是否为空
        if(userVO.getUserAccount() == null || userVO.getUserPassword() == null){
            throw new CustomException(ResultCode.USER_INFO_IS_NULL);
        }
......

标签:code,return,SpringBoot,自定义,ResultBean,ResultCode,resultCode,异常,public
来源: https://www.cnblogs.com/tanxj/p/16422024.html