spring boot 使用 ControllerAdvice处理全局异常

异常处理类,给前端返回异常信息的类,数据格式根据自己意愿随意组装:

@ControllerAdvice
@ResponseBody
public class ApiExceptionHandler {

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

    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception e) {
        logger.error("错误信息:",e);
        Map result = new HashMap();
        result.put("code",1);
        result.put("msg",e.getMessage());
        return result;
    }

    @ExceptionHandler(value = SelfRunException.class)
    public Map errorSelfException(SelfRunException e) throws Exception{
        logger.error("错误信息:",e);
        Map result = new HashMap();
        result.put("code",e.getCode());
        result.put("msg",e.getMsg());
        return result;
    }

}

 书写测试类开始测试:

@Controller
public class ControllerAdviceTest {

    private static final Logger logger = LoggerFactory.getLogger(ControllerAdviceTest.class);
    /**
       测试没有自定义异常的异常
      /
    @RequestMapping(value = "/testControllerAdvice")
    @ResponseBody
    public Map testControllerAdvice() {
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","正确");

        int a = 1 / 0;  // 故意制造异常
        return map;
    }
    

    /**
       测试自定义异常
    /
    @RequestMapping(value = "/testConAdvSelfException")
    @ResponseBody
    public Map testConAdvSelfException() {
        Map map = new HashMap();
        if(1 == 2) {
            map.put("code",0);
            map.put("msg","正确");
            return map;
        }else{
            throw  new SelfRunException("判断错误",1);
        }
    }
}

  先测试没有自定义异常的方法:

  localhost:8086/testControllerAdvice

  

  测试自定义异常方法:

  localhost:8086/testConAdvSelfException

  

 

  自定义异常类:

@Data
public class SelfRunException extends RuntimeException{

    private String msg;
    private int code;
    private Object data;

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

}

  

 

 

你可能感兴趣的:(spring boot 使用 ControllerAdvice处理全局异常)