SpringMVC中的统一异常处理-自定义异常

https://www.cnblogs.com/shanheyongmu/p/5872442.htmlhtml

咱们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者经过捕获异常从而获取异常信息,后者主要经过规范代码开发、测试经过手段减小运行时异常的发生。在开发中,不论是dao层、service层仍是controller层,都有可能抛出异常,在springmvc中,能将全部类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。这篇博文主要总结一下SpringMVC中如何统一处理异常。前端

1. 异常处理思路

  首先来看一下在springmvc中,异常处理的思路(我已尽力画好看点了,不要喷我~): java


  如上图所示,系统的dao、service、controller出现异常都经过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。明白了springmvc中的异常处理机制,下面就开始分析springmvc中的异常处理。web

2. springmvc中自带的简单异常处理器(方式一)

  springmvc中自带了一个异常处理器叫SimpleMappingExceptionResolver,该处理器实现了HandlerExceptionResolver 接口,全局异常处理器都须要实现该接口。咱们要使用这个自带的异常处理器,首先得在springmvc.xml文件中配置该处理器:spring

<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
     <!-- 定义默认的异常处理页面 -->
    <property name="defaultErrorView" value="/WEB-INF/jsp/error.jsp"/>
    <!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception --> 
    <property name="exceptionAttribute" value="ex"/>
    <!-- 定义须要特殊处理的异常,这是重要点 --> 
    <property name="exceptionMappings">
        <props>
            <prop key="ssm.exception.CustomException">/WEB-INF/jsp/custom_error.jsp</prop>
        </props>
        <!-- 还能够定义其余的自定义异常 -->
    </property>
</bean>

从上面的配置来看,最重要的是要配置特殊处理的异常,这些异常通常都是咱们自定义的,根据实际状况来自定义的异常,而后也会跳转到不一样的错误显示页面显示不一样的错误信息。这里就用一个自定义异常CustomException来讲明问题,定义以下:数据库

本身定义本身抛出throw new Exception();json

//定义一个简单的异常类
public class CustomException extends Exception {

    //异常信息
    public String message;

    public CustomException(String message) {
        super(message);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

接下来就是写测试程序了,仍是使用查询的例子,以下: 
异常 
  而后咱们在前台输入url来测试:http://localhost:8080/SpringMVC_Study/editItems.action?id=11,故意传一个id为11,个人数据库中没有id为11的项,因此确定查不到,反正让它查不到便可。这样它就会抛出自定义的异常,而后被上面配置的全局异常处理器捕获并执行,跳转到咱们指定的页面,而后显示一下该商品不存在便可。因此这个流程是很清晰的。 
  从上面的过程可知,使用SimpleMappingExceptionResolver进行异常处理,具备集成简单、有良好的扩展性(能够任意增长自定义的异常和异常显示页面)、对已有代码没有入侵性等优势,但该方法仅能获取到异常信息,若在出现异常时,对须要获取除异常之外的数据的状况不适用。mvc

3. 自定义全局异常处理器(方式二与方式一相似)

  全局异常处理器处理思路:app

  1. 解析出异常类型
  2. 若是该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展现
  3. 若是该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)

springmvc提供一个HandlerExceptionResolver接口,自定义全局异常处理器必需要实现这个接口,以下:jsp

配置上方本身定义的异常

public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {

        ex.printStackTrace();
        CustomException customException = null;

        //若是抛出的是系统自定义的异常则直接转换,也就是本身抛出的throw new Exception();
        if(ex instanceof CustomException) {
            customException = (CustomException) ex;
        } else {
            //若是抛出的不是系统自定义的异常则从新构造一个未知错误异常
            //这里我就也有CustomException省事了,实际中应该要再定义一个新的异常
            customException = new CustomException("系统未知错误");
        }

        //向前台返回错误信息
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", customException.getMessage());
        modelAndView.setViewName("/WEB-INF/jsp/error.jsp");

        return modelAndView;
    }
}

全局异常处理器中的逻辑很清楚,我就再也不多说了,而后就是在springmvc.xml中配置这个自定义的异常处理器:

<!-- 自定义的全局异常处理器 
只要实现HandlerExceptionResolver接口就是全局异常处理器-->
<bean class="ssm.exception.CustomExceptionResolver"></bean>

而后就可使用上面那个测试用例再次测试了。能够看出在自定义的异常处理器中能获取致使出现异常的对象,有利于提供更详细的异常处理信息。通常用这种自定义的全局异常处理器比较多。

4. 使用 @ ExceptionHandler 注解(方式二)

使用该注解有一个很差的地方就是:进行异常处理的方法必须与出错的方法在同一个Controller里面。使用以下:

@Controller      
 public class GlobalController {               
 
    /**    
      * 用于处理异常的    
      * @return    
      */      
     @ExceptionHandler({MyException.class})       
     public String exception(MyException e) {       
         System.out.println(e.getMessage());       
         e.printStackTrace();       
         return "exception";       
     }       
 
     @RequestMapping("test")       
     public void test() {       
         throw new MyException("出错了!");       
     }                    
 }

 

能够看到,这种方式最大的缺陷就是不能全局控制异常。每一个类都要写一遍。

5.使用 @ControllerAdvice+ @ ExceptionHandler 注解(方式三)

上文说到 @ ExceptionHandler 须要进行异常处理的方法必须与出错的方法在同一个Controller里面。那么当代码加入了 @ControllerAdvice,则不须要必须在同一个 controller 中了。这也是 Spring 3.2 带来的新特性。从名字上能够看出大致意思是控制器加强。 也就是说,@controlleradvice + @ ExceptionHandler 也能够实现全局的异常捕捉。

请确保此WebExceptionHandle 类能被扫描到并装载进 Spring 容器中。

@ControllerAdvice
@ResponseBody
public class WebExceptionHandle {
private static Logger logger = LoggerFactory.getLogger(WebExceptionHandle.class);
 /**
  * 400 - Bad Request
  */
 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ExceptionHandler(HttpMessageNotReadableException.class)
  public ServiceResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
      logger.error("参数解析失败", e);
      return ServiceResponseHandle.failed("could_not_read_json");
  }
  
  /**
   * 405 - Method Not Allowed
   */
  @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
  @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  public ServiceResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
      logger.error("不支持当前请求方法", e);
      return ServiceResponseHandle.failed("request_method_not_supported");
  }

  /**
   * 415 - Unsupported Media Type
   */
  @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
  @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
  public ServiceResponse handleHttpMediaTypeNotSupportedException(Exception e) {
      logger.error("不支持当前媒体类型", e);
      return ServiceResponseHandle.failed("content_type_not_supported");
  }

  /**
   * 500 - Internal Server Error
   */
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ExceptionHandler(Exception.class)
  public ServiceResponse handleException(Exception e) {
      if (e instanceof BusinessException){
          return ServiceResponseHandle.failed("BUSINESS_ERROR", e.getMessage());
      }
      
      logger.error("服务运行异常", e);
      e.printStackTrace();
      return ServiceResponseHandle.failed("server_error");
    }
} 

若是 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为参数列表中的异常类型。因此还能够写成这样:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler()
    @ResponseBody
    String handleException(Exception e){
        return "Exception Deal! " + e.getMessage();
    }
}

参数对象就是 Controller 层抛出的异常对象!

继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,而且能够返回自定义格式:

@Slf4j
 @ControllerAdvice
 public class ExceptionHandlerBean  extends ResponseEntityExceptionHandler {

   /**
    * 数据找不到异常
    * @param ex
    * @param request
    * @return
     * @throws IOException
     */
    @ExceptionHandler({DataNotFoundException.class})
    public ResponseEntity<Object> handleDataNotFoundException(RuntimeException ex, WebRequest request) throws IOException {
        return getResponseEntity(ex,request,ReturnStatusCode.DataNotFoundException);
    }

    /**
     * 根据各类异常构建 ResponseEntity 实体. 服务于以上各类异常
     * @param ex
     * @param request
     * @param specificException
     * @return
     */
    private ResponseEntity<Object> getResponseEntity(RuntimeException ex, WebRequest request, ReturnStatusCode specificException) {

        ReturnTemplate returnTemplate = new ReturnTemplate();
        returnTemplate.setStatusCode(specificException);
        returnTemplate.setErrorMsg(ex.getMessage());

        return handleExceptionInternal(ex, returnTemplate,
                new HttpHeaders(), HttpStatus.OK, request);
    }

} 

以上就是 Spring 处理程序统一异常的三种方式。

相关文章
相关标签/搜索