【SpringMVC 从 0 开始】异常处理器

一、基于配置的异常处理

SpringMVC 提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver

HandlerExceptionResolver接口的实现类有:

  • DefaultHandlerExceptionResolver,这个是默认使用的处理器,之前遇到的一些异常,其实springMVC 都已经给我们处理过了。
  • SimpleMappingExceptionResolver,这个可以让我们自定义异常处理。当出现指定的异常,可以设置返回新的视图。

使用SimpleMappingExceptionResolver,在springMVC的配置文件中:

  <!--配置异常处理-->
  <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
          <props>
              <prop key="java.lang.ArithmeticException">error</prop>
          </props>
      </property>
  </bean>
  • 示例里使用的一个处理运算异常的类ArithmeticException,里面的值 error 表示异常后跳转的视图。

对应的,新建一个error.html页:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
出现错误
</body>
</html>

接下来,造一个异常:

  @RequestMapping("/testExceptionHandler")
  public String testExceptionHandler() {
      System.out.println(1/0);
      return "success";
  }

正常情况下这个处理器会跳转到 success 页,但是里面有个 1/0的异常,所以会按照配置跳转到 error 页。

重新部署,测试一下,访问http://localhost:8080/springmvc/testExceptionHandler

成功跳转到 error 页。

储存异常信息

此外,还可以继续属性exceptionAttribute,设置一个key用来存放异常信息,默认存在当前的请求域中:

  <!--配置异常处理-->
  <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
          <props>
              <prop key="java.lang.ArithmeticException">error</prop>
          </props>
      </property>
      <!--exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享-->
      <property name="exceptionAttribute" value="ex"></property>
  </bean>

那么在 error 页中就可以使用到ex来获取异常信息了。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
出现错误
<p th:text="${ex}"></p>
</body>
</html>

重新部署,刷新下页面:

二、基于注解的异常处理

springmvc 同样也提供了一套注解,通过注解方式也可以实现上述的异常处理。

新建一个控制器 ExceptionController:

//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {

    //@ExceptionHandler 用于设置所标识方法处理的异常
    @ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
    public String testException(Exception ex, Model model){
        // ex表示当前请求处理中出现的异常对象,放到请求域中
        model.addAttribute("ex", ex);
        return "error";
    }
}
  • @ControllerAdvice将当前类标识为异常处理的组件。
  • ex表示当前请求处理中出现的异常对象,用Model放到请求域中。

现在注释掉配置文件里的处理器,重新部署下,刷新http://localhost:8080/springmvc/testExceptionHandler

依然可以。

posted @   把苹果咬哭的测试笔记  阅读(46)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示