ControllerAdvice注解的使用

女爷i 2022-05-25 01:39 343阅读 0赞

为了方便对异常的统一管理,spring mvc提供了ControllerAdvice注解对异常进行统一的处理,拿到这些异常信息后,可以做一些处理,比如提供一个统一的web界面查看异常信息,或者普通到异常信息后,发送短信、邮件形式通知到相关人员,可以帮助开发人员快速发现并定位问题,减少以往通过查看线上日志文件排查问繁琐锁耗时的所耗费的时间。下面我跟大家介绍具体步骤。

配置

spring 版本:

  1. <org.springframework-version>4.1.9.RELEASE</org.springframework-version>

spring-servlet.xml,注意必须开启注解,即xml要有

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  3. <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
  4. <!-- Enables the Spring MVC @Controller programming model -->
  5. <annotation-driven />
  6. <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
  7. <resources mapping="/resources/**" location="/resources/" />
  8. <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
  9. <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  10. <beans:property name="prefix" value="/WEB-INF/views/" />
  11. <beans:property name="suffix" value=".jsp" />
  12. </beans:bean>
  13. <context:component-scan base-package="org.as.asjee" use-default-filters="false">
  14. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  15. </context:component-scan>
  16. </beans:beans>

异常统一处理类

  1. package org.as.asjee.core.exception;
  2. import java.sql.SQLException;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.as.asjee.core.log.AsJEELogger;
  5. import org.as.asjee.core.log.AsJEELoggerFactory;
  6. import org.springframework.web.bind.annotation.ControllerAdvice;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import org.springframework.web.servlet.ModelAndView;
  10. /** * 捕获异常统一处理 * @description TODO * @author chen.gs * @create date 2016年4月28日 * @modified by * @modify date * @version v1.0 */
  11. @ControllerAdvice
  12. public class GlobalExceptionHandler {
  13. private final static AsJEELogger LOG = AsJEELoggerFactory.getLogger(GlobalExceptionHandler.class);
  14. private final static String EXPTION_MSG_KEY = "message";
  15. @ExceptionHandler(BusinessException.class)
  16. @ResponseBody
  17. public void handleBizExp(HttpServletRequest request, Exception ex){
  18. LOG.info("Business exception handler " + ex.getMessage() );
  19. request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());
  20. }
  21. @ExceptionHandler(SQLException.class)
  22. public ModelAndView handSql(Exception ex){
  23. LOG.info("SQL Exception " + ex.getMessage());
  24. ModelAndView mv = new ModelAndView();
  25. mv.addObject("message", ex.getMessage());
  26. mv.setViewName("sql_error");
  27. return mv;
  28. }
  29. }

自定义异常类BussinessException.java

  1. package org.as.asjee.core.exception;
  2. /** * 业务异常 * @description TODO * @author chen.gs * @create date 2016年4月28日 * @modified by * @modify date * @version v1.0 */
  3. public class BusinessException extends Exception{
  4. private static final long serialVersionUID = 1L;
  5. //业务类型
  6. private String bizType;
  7. //业务代码
  8. private int bizCode;
  9. //错误信息
  10. private String message;
  11. public BusinessException(String bizType, int bizCode, String message){
  12. super(message);
  13. this.bizType = bizType;
  14. this.bizCode = bizCode;
  15. this.message = message;
  16. }
  17. public BusinessException(String message){
  18. super(message);
  19. this.bizType = "";
  20. this.bizCode = -1;
  21. this.message = message;
  22. }
  23. public BusinessException(String bizType, String message){
  24. super(message);
  25. this.bizType = bizType;
  26. this.bizCode = -1;
  27. this.message = message;
  28. }
  29. public BusinessException(int bizCode, String message){
  30. super(message);
  31. this.bizType = "";
  32. this.bizCode = bizCode;
  33. this.message = message;
  34. }
  35. public String getBizType() {
  36. return bizType;
  37. }
  38. public void setBizType(String bizType) {
  39. this.bizType = bizType;
  40. }
  41. public int getBizCode() {
  42. return bizCode;
  43. }
  44. public void setBizCode(int bizCode) {
  45. this.bizCode = bizCode;
  46. }
  47. public String getMessage() {
  48. return message;
  49. }
  50. public void setMessage(String message) {
  51. this.message = message;
  52. }
  53. }

controller

  1. package org.as.asjee.core.security.web;
  2. import java.sql.SQLException;
  3. import javax.annotation.Resource;
  4. import org.as.asjee.core.exception.BusinessException;
  5. import org.as.asjee.core.security.model.User;
  6. import org.as.asjee.core.security.service.UserService;
  7. import org.as.asjee.core.service.ServiceFacade;
  8. import org.as.asjee.core.web.AbstractController;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. @Controller
  12. @RequestMapping("/security/user")
  13. public class UserController extends AbstractController<User>{
  14. @Resource
  15. private UserService userService;
  16. @Resource
  17. private ServiceFacade serviceFacade;
  18. @RequestMapping("login")
  19. public String login() {
  20. return "login";
  21. }
  22. @RequestMapping("login2")
  23. public String login2() throws Exception {
  24. throw new SQLException("出错鸟。。。。。。。。。");
  25. }
  26. @RequestMapping("login3")
  27. public String login3() throws Exception {
  28. throw new BusinessException("业务执行异常");
  29. }
  30. //此方法抛出的异常不是由GlobalExceptionHandler处理
  31. //而是在catch块处理
  32. @RequestMapping("login4")
  33. public String login4() {
  34. try {
  35. throw new BusinessException("业务执行异常");
  36. } catch (BusinessException e) {
  37. e.printStackTrace();
  38. }
  39. return "login";
  40. }
  41. }

简要说明

在Controller中抛出的异常,当没有被catch处理时,GlobalExceptionHandler中定义的处理方法可以起作用,在方法写明注解@ExceptionHandler,并注明其异常类即可。此种方法不仅可以作用于Controller,同样的在DAO层、service层也可,都可以由GlobalExceptionHandler进行处理。此种写法减少代码的入侵,值得推荐。
异常的统一处理只是注解ControllerAdvice用处之一,有兴趣了解更多的,请到spring官网查阅。

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ControllerAdvice注解使用

    为了方便对异常的统一管理,spring mvc提供了ControllerAdvice注解对异常进行统一的处理,拿到这些异常信息后,可以做一些处理,比如提供一个统一的web界面查