在spring 3.2中,新增了@ControllerAdvice 注解,可以用於定義@ExceptionHandler、@InitBinder、@ModelAttribute,並應用到所有@RequestMapping中。
/** * 全局異常處理器 * * @author*/ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 權限校驗失敗 如果請求為ajax返回json,普通請求跳轉頁面 */ @ExceptionHandler(AuthorizationException.class) public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) { log.error(e.getMessage(), e); if (ServletUtils.isAjaxRequest(request)) { return AjaxResult.error(PermissionUtils.getMsg(e.getMessage())); } else { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error/unauth"); return modelAndView; } } /** * 請求方式不支持 */ @ExceptionHandler({ HttpRequestMethodNotSupportedException.class }) public AjaxResult handleException(HttpRequestMethodNotSupportedException e) { log.error(e.getMessage(), e); return AjaxResult.error("不支持' " + e.getMethod() + "'請求"); } /** * 攔截未知的運行時異常 */ @ExceptionHandler(RuntimeException.class) public AjaxResult notFount(RuntimeException e) { log.error("運行時異常:", e); return AjaxResult.error("運行時異常:" + e.getMessage()); } /** * 系統異常 */ @ExceptionHandler(Exception.class) public AjaxResult handleException(Exception e) { log.error(e.getMessage(), e); return AjaxResult.error("服務器錯誤,請聯系管理員"); } /** * 業務異常 */ @ExceptionHandler(BusinessException.class) public Object businessException(HttpServletRequest request, BusinessException e) { log.error(e.getMessage(), e); if (ServletUtils.isAjaxRequest(request)) { return AjaxResult.error(e.getMessage()); } else { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errorMessage", e.getMessage()); modelAndView.setViewName("error/business"); return modelAndView; } } /** * 自定義驗證異常 */ @ExceptionHandler(BindException.class) public AjaxResult validatedBindException(BindException e) { log.error(e.getMessage(), e); String message = e.getAllErrors().get(0).getDefaultMessage(); return AjaxResult.error(message); } }