自定义异常处理

系统自定义异常处理

复制代码
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public ResponseResult ariHandleException(){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0).setMsg("格式转换异常");
        return responseResult;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult handleException(Exception e){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0).setMsg(e.getMessage());
        return responseResult;
    }



}
复制代码

简单说明:异常越精确,越能知道此类异常的处理,如果没有特殊处理的,就是Exception。异常类型写在@ExceptionHandler(ArithmeticException.class)里面。

比如如果抛出异常ArithmeticException,那么就会走第一种方法,如果是别的异常,没有特殊处理的,那就走第二种方法。

下面是响应对象。

复制代码
@Data
@Slf4j
@Accessors(chain = true)
public class ResponseResult implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code;

    private String msg;

    private Object data;

    public static ResponseResult success(int code,String msg,Object data){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(code).setMsg(msg).setData(data);
        return responseResult;
    }

    public static ResponseResult success(Object data){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200).setMsg("").setData(data);
        return responseResult;
    }

    public static ResponseResult success(){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200).setMsg("请求成功").setData(null);
        return responseResult;
    }

    public static ResponseResult success(int code,String msg){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(code).setMsg(msg).setData(null);
        return responseResult;
    }



    public static ResponseResult fail(int code,String msg,Object data){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(code).setMsg(msg).setData(data);
        return responseResult;
    }


    public static ResponseResult fail(int code,String msg){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(code).setMsg(msg).setData(null);
        return responseResult;
    }

    public static ResponseResult fail(){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(-1).setMsg("请求失败").setData(null);
        return responseResult;
    }

}
复制代码

测试的controller

ArithmeticException异常

Exception异常

 测试结果

 

posted @   多多指教~  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示