/**
* Created by PengWX on 2019/9/23.
* 全局捕获异常类,所有@RequestMapping上,所有的异常都会被捕获
*/
@ResponseBody
@ControllerAdvice
public class MyGlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public Map<String, Object> errorHandle(Exception e) {
//可以使用try-catch方式也可以使用 if (e instanceof BizException)方式,也可以每种异常写一个@ExceptionHandler
JSONObject jsonObject = new JSONObject();
try {
throw e;
} catch (BizException e1) {
jsonObject.put("code", 20000);
jsonObject.put("msg", e.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
jsonObject.put("code", 30000);
jsonObject.put("msg", e.getMessage());
e1.printStackTrace();
}
return jsonObject;
}
/**
* 自己定义的exception处理,有具体的xxxException会先使用具体的handler,不然就是使用ExceptionHandler
*
* @param e
* @return
*/
/* @ExceptionHandler(value = BizException.class)
public Map<String, Object> bizExceptionHandle(BizException e) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 20000);
jsonObject.put("msg", e.getMessage());
return jsonObject;
}*/
}
然后直接抛出异常测试
@RequestMapping("test")
@ResponseBody
public Integer test() {
Integer num = 1 / 0;
return num;
}
@RequestMapping("testHanlderBiz")
@ResponseBody
public Integer testHanlderBiz() {
Integer num = null;
try {
num = 1 / 0;
} catch (BizException e) {
e.printStackTrace();
throw new BizException(e.getMessage());
}
return num;
}
@ExceptionHandler注解。
当一个Controller中有方法加了@ExceptionHandler之后,这个Controller其他方法中没有捕获的异常就会以参数的形式传入加了@ExceptionHandler注解的那个方法中。配合使用@ControllerAdvice实现aop增强的方式全局处理异常
@ControllerAdvice抽象级别应该是用于对Controller进行“切面”环绕的,而具体的业务织入方式则是通过结合其他的注解来实现的。