14SpringMVC中的默认的异常解析器,以及如何基于XML和注解的方式配置自定义异常解析器

异常处理器

默认异常解析器

控制器方法执行过程中如果出现了异常,此时就可以使用SpringMVC提供的HandlerExceptionResolver接口帮助我们处理出现的异常

  • HandlerExceptionResolver接口有DefaultHandlerExceptionResolver(默认)和SimpleMappingExceptionResolver(自定义)两种实现类

DefaultHandlerExceptionResolver的doResolveException方法处理完控制器方法中出现的异常后会返回一个新的ModelAndView对象用来跳转到指定的异常页面

@Nullable
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
        try {
            // 处理请求方式不被支持的异常
            if (ex instanceof HttpRequestMethodNotSupportedException) {
                return this.handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex, request, response, handler);
            }

            if (ex instanceof HttpMediaTypeNotSupportedException) {
                return this.handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException)ex, request, response, handler);
            }

            if (ex instanceof HttpMediaTypeNotAcceptableException) {
                return this.handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException)ex, request, response, handler);
            }

            if (ex instanceof MissingPathVariableException) {
                return this.handleMissingPathVariable((MissingPathVariableException)ex, request, response, handler);
            }
            //........
        } catch (Exception var6) {
            if (this.logger.isWarnEnabled()) {
                this.logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", var6);
            }
        }

        return null;
    }

自定义异常解析器

配置SpringMVC提供的自定义异常处理器SimpleMappingExceptionResolver需要设置两个属性

设置Properties集合类型的exceptionMappings属性

  • properties的键是异常的全类名表示处理器方法执行过程中出现哪种异常时才会被异常解析器处理
  • properties的值是视图名称: 表示若出现指定异常时要跳转到的页面,此时依然遵循视图解析器的规则

设置String类型的exceptionAttribute属性用来把异常对象共享到请求域中,所以我们需要设置一个key将来才能在页面中通过这个key获取到请求域中的异常对象的信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <!--设置出现数学运算异常时跳转到error.html页面-->
            <prop key="java.lang.ArithmeticException">error</prop>
        </props>
    </property>
    <!--将控制器方法出现的异常对象存放到请求域中同时指定key-->
    <property name="exceptionAttribute" value="ex"></property>
</bean>

编写控制器方法模拟数学运算异常,指定跳转到的异常页面并展示异常信息

@RequestMapping("/testExceptionHandler")
public String testExceptionHandler(){
    System.out.println(1/0);
    return "success";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
出现错误
<!--获取异常信息-->
<p th:text="${ex}"></p>
</body>
</html>

基于注解的异常处理

@ControllerAdvice注解是@Controller的扩展注解,也可以将当前类标识为异常处理的组件,一般会放在controller包下

@ExceptionHandler注解的value属性可以用来指定一个或多个异常,当控制器方法执行过程中出现了指定类型的异常就会执行其所标识的控制器方法

  • Exception(Throwable) ex: 对于控制器方法执行中出现的异常信息对象,我们只要在控制器方法中声明对应形参前端控制器会自动注入Exception类型的对象
@ControllerAdvice
public class ExceptionController {
    // 设置所标识方法处理的异常
    @ExceptionHandler(ArithmeticException.class)
    public String handleArithmeticException(Throwable ex, Model model){
        // 将异常对象放在请求域中共享
        model.addAttribute("ex", ex);
        // 设置出现异常后跳转的页面
        return "error";
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值