其他分享
首页 > 其他分享> > springboot 自定义异常

springboot 自定义异常

作者:互联网

生名一个异常类:

比如用户登录授权异常类:

/**
 * 自定义业务异常对象
 */
public class AuthorizationException extends RuntimeException {

    /**
     * @Fields serialVersionUID : TODO
     */
    private static final long serialVersionUID = 1L;

    private int code;

    private Object data;

    /*
     * 默认异常
     */
    public AuthorizationException() {
        this(200,"请求成功");
    }

    public AuthorizationException(int code, String msg) {
        super(msg);
        this.code = code;
    }

    public AuthorizationException(int code, String msg, Object data) {
        super(msg);
        this.code = code;
        this.data = data;
    }

    public AuthorizationException(String message) {
        super(message);
        code = 420;
    }

    public int getCode() {
        return code;
    }

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

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
    
}

 

声明一个全局异常处理类:RestControllerAdvice.java

/**
 * 全局异常处理类,处理系统内所有异常,并给客户端相关的响应.
 */
@ControllerAdvice
public class RestControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(RestControllerAdvice.class);

    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public JsonResponse<?> handleBusinessException(AuthorizationException ex, HttpServletResponse response) {
        logger.error(ex.getMessage(),ex);
        return new JsonResponse<>(ex.getCode(),ex.getMessage(), ex.getData());
    }
    
}

JsonResponse.java
@Data
public class JsonResponse<T> {

    Integer code;

    String message;
    
    T data;
    

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

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

 

在业务层抛出 刚才声明的AuthorizationException异常:


@RequestMapping("/test")
public Boolean test(){throw new AuthorizationException(401, "未登录"); }

这样就完成啦

 

标签:code,springboot,自定义,AuthorizationException,异常,JsonResponse,message,data,public
来源: https://www.cnblogs.com/wanjun-top/p/12974142.html