我看过很多 SpringMVC 的项目,很多是没有异常处理的。本文将教你如何通过@ExceptionHandler 注解来进行处理。
更多精彩内容请看 web 前端中文站
http://www.lisa33xiaoq.net 可按 Ctrl + D 进行收藏
@ExceptionHandler 可以统一处理一个 Controller 中抛出的异常,可以统一处理所有 Controller 中抛出的异常。
该注解作用对象为方法,并且在运行时有效,value()可以指定异常类。由该注解注释的方法可以具有灵活的输入参数(详细参见 Spring API):
- 异常参数:包括一般的异常或特定的异常(即自定义异常),如果注解没有指定异常类,会默认进行映射。
- 请求或响应对象 (Servlet API or Portlet API): 你可以选择不同的类型,如 ServletRequest/HttpServletRequest 或 PortleRequest/ActionRequest/RenderRequest
。
- Session 对象(Servlet API or Portlet API): HttpSession 或 PortletSession。
- WebRequest 或 NativeWebRequest
- Locale
- InputStream/Reader
- OutputStream/Writer
- Model
方法返回值可以为:
- ModelAndView 对象
- Model 对象
- Map 对象
- View 对象
- String 对象
- 还有@ResponseBody、HttpEntity<?>或 ResponseEntity<?>,以及 void
@ExceptionHandler 的使用很简单,用法如下面的代码:
/** * 统一异常处理 * @param request * @param response * @param exception */ @ExceptionHandler public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) { _log.error("统一异常处理:", exception); request.setAttribute("ex", exception); if (null != request.getHeader("X-Requested-With") && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) { request.setAttribute("requestHeader", "ajax"); } // shiro 没有权限异常 if (exception instanceof UnauthorizedException) { return "/403.jsp"; } // shiro 会话已过期异常 if (exception instanceof InvalidSessionException) { return "/error.jsp"; } return "/error.jsp"; }
如果要做到全局 Controller 异常处理,只需要新建一个 Controller 让其他 Controller 继承该 Controller 即可。
上面的代码只要 Controller 中有异常,都会被 exceptionHandler 方法扑获并执行。
Spring 有 3 个异常处理的注解,分别如下:
- @ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度
- @ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开
- @ResponseStatus:可以将某种异常映射为 HTTP 状态码
@ControllerAdvice 注解作用对象为 TYPE,包括类、接口和枚举等,在运行时有效,并且可以通过 Spring 扫描为 bean 组件。其可以包含由@ExceptionHandler、@InitBinder 和@ModelAttribute 标注的方法,可以处理多个 Controller 类,这样所有控制器的异常可以在一个地方进行处理。
@ExceptionHandler 和@ControllerAdvice 能够集中异常,使异常处理与业务逻辑分离。
本文原文出处:web 前端中文站: » Spring 中@ExceptionHandler 注解使用教程
【注:本文源自网络文章资源,由站长整理发布】