@ControllerAdvice
public class MyException {
@ExceptionHandler(UnauthorizedException.class)
public String UnauthorizedException(RuntimeException e, HandlerMethod handlerMethod, HttpServletResponse resp) throws IOException {
e.printStackTrace();
//1. 获取到当前出现异常的方法
//直接在参数定义HandlerMethod
//2. 判断该方法上面是否有@ResponseBody注解
//ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
//这个方法直接返回boolean类型
boolean flag = handlerMethod.hasMethodAnnotation(ResponseBody.class);
//如有,处理异步请求的异常
if (flag){
JsonResult jsonResult = new JsonResult(false, "操作失败,请咨询110");
//将jsonResult格式化为json格式的字符串,存储到jsonString中
String jsonString = JSON.toJSONString(jsonResult);
//设置写回客户端的格式及字符集
resp.setContentType("application/json;charset=UTF-8");
//将json数据返回到客户端浏览器
resp.getWriter().write(jsonString);
return null;
}
//如果没有,处理页面跳转请求的异常
else {
return "common/nopermission";
}
}
@ExceptionHandler(RuntimeException.class)
public String runtimeException(HandlerMethod handlerMethod,HttpServletResponse response) throws IOException {
//判断执行方法是否含有ResponseBody注解
boolean flag = handlerMethod.hasMethodAnnotation(ResponseBody.class);
if (flag){
//含有,返回json格式的字符串
JsonResult js = new JsonResult(false,"操作失败");
String str = JSON.toJSONString(js);
response.getWriter().write(str);
return null;
}else {
//返回错误页面
return "common/error";
}
}
}