码迷,mamicode.com
首页 > 编程语言 > 详细

springboot 自定义异常

时间:2020-05-27 17:04:36      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:一个   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<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, "未登录"); }

这样就完成啦

 

springboot 自定义异常

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!