springboot 自定义异常

2021-01-07 03:30

阅读:615

标签:一个   int   serial   客户端   etl   定义   ons   ice   etc   

生名一个异常类:

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

/**
 * 自定义业务异常对象
 */
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 {

    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, "未登录"); }

这样就完成啦

 

springboot 自定义异常

标签:一个   int   serial   客户端   etl   定义   ons   ice   etc   

原文地址:https://www.cnblogs.com/wanjun-top/p/12974142.html


评论


亲,登录后才可以留言!