自定义异常
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
定义通用的数据返回对象
public class ResultBean<T> {
private int code;
private String message;
private Collection<T> data;
private ResultBean() {
}
public static ResultBean error(int code, String message) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(1);
resultBean.setMessage(message);
return resultBean;
}
public static ResultBean success() {
ResultBean resultBean = new ResultBean();
resultBean.setCode(0);
resultBean.setMessage("success");
return resultBean;
}
public static <V> ResultBean<V> success(Collection<V> data) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(0);
resultBean.setMessage("success");
resultBean.setData(data);
return resultBean;
}
// getter / setter 略
}
全局异常拦截
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
@ExceptionHandler(value = MyException.class)
@ResponseBody
public ResultBean<String> errorHandler(HttpServletRequest req, MyException e) throws Exception {
ResultBean<String> result = new ResultBean<>();
result.setMessage(e.getMessage());
result.setCode(ErrorInfo.ERROR);
result.setData("Some Data");
return result;
}
}
使用
@RequestMapping("/test")
public String json() throws MyException {
throw new MyException("error!!!");
}