自定义异常处理

系统自定义异常处理

@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 @ 2024-02-21 15:54  多多指教~  阅读(1)  评论(0编辑  收藏  举报