详解SpringMVC中的异常处理

 更新时间:2021年03月23日 10:26:27   作者:柠檬时间  
这篇文章主要介绍了SpringMVC中的异常处理的相关资料,帮助大家更好的理解和学习使用SpringMVC,感兴趣的朋友可以了解下

1. SpringMVC默认三个异常处理类

  • ExceptionHandlerExceptionResolver:处理@ExceptionHandler注解
  • ResponseStatusExceptionResolver:处理@ResponseStatus注解
  • DefaultHandlerExceptionResolver:处理SpringMVC自带的异常

如果以上3个异常解析器都无法处理,会上抛给tomcat,处理异常内部的默认工作流程:所有异常解析器依次尝试解析,解析完成进行后续操作,解析失败,下一个解析器继续尝试解析。

2. @ExceptionHandler注解异常

@ExceptionHandler标注在方法上

  • 方法上写一个Exception用来接收发生的异常。
  • 要携带异常信息不能给参数位置写Model,正确的做法是返回ModelAndView。
  • 如果有多个@ExceptionHandler都能处理这个异常,精确优先。
@ExceptionHandler(value = { ArithmeticException.class, NullPointerException.class }) 
// 告诉SpringMVC,这个方法专门处理这个类发送的所有异常
public ModelAndView handleException01(Exception exception) {
  System.out.println("handleException01..." + exception);
  ModelAndView view = new ModelAndView("myerror");
  view.addObject("ex", exception);  
  return view;
}

@ExceptionHandler统一异常处理

  • 将@ExceptionHandler放在一个单独的类中,进行全局异常处理
  • 统一异常管理类需要通过@ControllerAdvice注解加入IoC容器中
  • 全局异常处理与本类异常处理同时存在,本类优先
@ControllerAdvice
public class MyException {
  // 处理空指针异常
  @ExceptionHandler(value = { NullPointerException.class })
  public ModelAndView handleException01(Exception exception) {
    System.out.println("全局的handleException01..." + exception);
    ModelAndView view = new ModelAndView("myerror");
    view.addObject("ex", exception);
    return view;
  }

  // 处理算数异常
  @ExceptionHandler(value = { ArithmeticException.class })
  public ModelAndView handleException02(Exception exception) {
    System.out.println("全局的handleException02..." + exception);
    ModelAndView view = new ModelAndView("myerror");
    view.addObject("ex", exception);
    return view;
  }
}

3. @ResponseStatus注解异常

@ResponseStatus注解标注在自定义异常上,用于设置自定义异常信息

@ResponseStatus(reason = "用户被拒绝登录", value = HttpStatus.NOT_ACCEPTABLE)
public class UsernameNotFoundException extends RuntimeException {
  private static final long serialVersionUID = 1L;
}

4. DefaultHandlerExceptionResolver默认异常

DefaultHandlerExceptionResolver包含以下默认异常

源码:
public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionResolver {
  ...
  @Override
  protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {

    try {
      if (ex instanceof NoSuchRequestHandlingMethodException) {
        return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response,
            handler);
      }
      else if (ex instanceof HttpRequestMethodNotSupportedException) {
        return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
            response, handler);
      }
      else if (ex instanceof HttpMediaTypeNotSupportedException) {
        return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response,
            handler);
      }
      else if (ex instanceof HttpMediaTypeNotAcceptableException) {
        return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, request, response,
            handler);
      }
      else if (ex instanceof MissingPathVariableException) {
        return handleMissingPathVariable((MissingPathVariableException) ex, request,
            response, handler);
      }
      else if (ex instanceof MissingServletRequestParameterException) {
        return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request,
            response, handler);
      }
      else if (ex instanceof ServletRequestBindingException) {
        return handleServletRequestBindingException((ServletRequestBindingException) ex, request, response,
            handler);
      }
      else if (ex instanceof ConversionNotSupportedException) {
        return handleConversionNotSupported((ConversionNotSupportedException) ex, request, response, handler);
      }
      else if (ex instanceof TypeMismatchException) {
        return handleTypeMismatch((TypeMismatchException) ex, request, response, handler);
      }
      else if (ex instanceof HttpMessageNotReadableException) {
        return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler);
      }
      else if (ex instanceof HttpMessageNotWritableException) {
        return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler);
      }
      else if (ex instanceof MethodArgumentNotValidException) {
        return handleMethodArgumentNotValidException((MethodArgumentNotValidException) ex, request, response,
            handler);
      }
      else if (ex instanceof MissingServletRequestPartException) {
        return handleMissingServletRequestPartException((MissingServletRequestPartException) ex, request,
            response, handler);
      }
      else if (ex instanceof BindException) {
        return handleBindException((BindException) ex, request, response, handler);
      }
      else if (ex instanceof NoHandlerFoundException) {
        return handleNoHandlerFoundException((NoHandlerFoundException) ex, request, response, handler);
      }
    }
    catch (Exception handlerException) {
      if (logger.isWarnEnabled()) {
        logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
      }
    }
    return null;
  }
  ...
}

如下HttpRequestMethodNotSupportedException请求方式不对。使用GET对POST方法进行访问

@RequestMapping(value = "/handle03", method = RequestMethod.POST)
public String postMethod() {
  return "success";
}

5. 没有找到对应异常处理类

若没有对应异常处理类,会进入对应服务器错误页面

以上就是详解SpringMVC中的异常处理的详细内容,更多关于SpringMVC 异常处理的资料请关注脚本之家其它相关文章!

相关文章

  • Java 中引入内部类的意义?

    Java 中引入内部类的意义?

    这篇文章主要介绍了Java 中引入内部类的意义?文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,,需要的朋友可以参考下
    2019-06-06
  • Java集合中的LinkedHashSet源码解读

    Java集合中的LinkedHashSet源码解读

    这篇文章主要介绍了Java集合中的LinkedHashSet源码解读,在LinkedHashMap中,双向链表的遍历顺序通过构造方法指定,如果没有指定,则使用默认顺序为插入顺序,即accessOrder=false,需要的朋友可以参考下
    2023-12-12
  • JDBC中Statement和Preparement的使用讲解

    JDBC中Statement和Preparement的使用讲解

    今天小编就为大家分享一篇关于JDBC中Statement和Preparement的使用讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Java数据结构之二叉查找树的实现

    Java数据结构之二叉查找树的实现

    二叉查找树(亦称二叉搜索树、二叉排序树)是一棵二叉树,且各结点关键词互异,其中根序列按其关键词递增排列。本文将通过示例详细讲解二叉查找树,感兴趣的可以了解一下
    2022-03-03
  • java计算两个日期之前的天数实例(排除节假日和周末)

    java计算两个日期之前的天数实例(排除节假日和周末)

    下面小编就为大家带来一篇java计算两个日期之前的天数实例(排除节假日和周末)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • springboot+mybaties项目中扫描不到@mapper注解的解决方法

    springboot+mybaties项目中扫描不到@mapper注解的解决方法

    本文主要介绍了springboot+mybaties项目中扫描不到@mapper注解的解决方法,该报错表明扫描不到Mapper层,具有一定的参考价值,感兴趣的可以了解一下
    2024-05-05
  • Java 中的 getDeclaredMethods() 方法(使用与原理)

    Java 中的 getDeclaredMethods() 方法(使用与原理)

    文章介绍了Java反射机制中的`getDeclaredMethods()`方法,详细讲解了其使用方法、原理、注意事项以及实际应用场景,帮助读者更好地理解和应用这一强大的工具,感兴趣的朋友一起看看吧
    2024-12-12
  • SpringBoot使用PropertiesLauncher加载外部jar包

    SpringBoot使用PropertiesLauncher加载外部jar包

    这篇文章主要介绍了SpringBoot使用PropertiesLauncher加载外部jar包,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • SpringBoot 集成MQTT实现消息订阅的详细代码

    SpringBoot 集成MQTT实现消息订阅的详细代码

    本文介绍了如何在SpringBoot中集成MQTT并实现消息订阅,主要步骤包括添加依赖、配置文件设置、启动类注解、MQTT配置类、消息处理器配置、主题缓存、动态数据库主题配置以及消息处理服务,感兴趣的朋友跟随小编一起看看吧
    2024-11-11
  • springboot图片验证码功能模块

    springboot图片验证码功能模块

    用户登录几乎是一个线上系统必不可少且使用相对比较频繁的一个模块,为了防止恶意暴力尝试,防止洪水攻击、防止脚本自动提交等,验证码是一个较为便捷且行之有效的预防手段,这篇文章主要介绍了springboot图片验证码功能模块,需要的朋友可以参考下
    2022-04-04

最新评论