@ControllerAdvice
public class MyException {
@ExceptionHandler(UnauthorizedException.class)
public String UnauthorizedException(RuntimeException e, HandlerMethod handlerMethod, HttpServletResponse resp) throws IOException {
e.printStackTrace();
//1. 獲取到當(dāng)前出現(xiàn)異常的方法
//直接在參數(shù)定義HandlerMethod
//2. 判斷該方法上面是否有@ResponseBody注解
//ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
//這個(gè)方法直接返回boolean類型
boolean flag = handlerMethod.hasMethodAnnotation(ResponseBody.class);
//如有,處理異步請求的異常
if (flag){
JsonResult jsonResult = new JsonResult(false, "操作失敗,請咨詢110");
//將jsonResult格式化為json格式的字符串,存儲到j(luò)sonString中
String jsonString = JSON.toJSONString(jsonResult);
//設(shè)置寫回客戶端的格式及字符集
resp.setContentType("application/json;charset=UTF-8");
//將json數(shù)據(jù)返回到客戶端瀏覽器
resp.getWriter().write(jsonString);
return null;
}
//如果沒有,處理頁面跳轉(zhuǎn)請求的異常
else {
return "common/nopermission";
}
}
@ExceptionHandler(RuntimeException.class)
public String runtimeException(HandlerMethod handlerMethod,HttpServletResponse response) throws IOException {
//判斷執(zhí)行方法是否含有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 {
//返回錯(cuò)誤頁面
return "common/error";
}
}
}