使用xml和注解配置异常处理

xml配置异常处理

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

  • SpringMVC有默认的异常处理器还可以自定义的异常处理器。

springmvc配置异常处理器

<!--   自定义异常处理器 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--     exceptionMappings:异常映射   -->
        <property name="exceptionMappings">
            <props>
<!--        key设置要处理的异常,value设置出现异常时要跳转的页面所对应的逻辑视图        -->
                <prop key="java.lang.ArithmeticException">error</prop>
            </props>
        </property>
<!--       设置在共享在请求域中的异常信息的属性名  就可以通过属性名访问当前属性值也就是异常信息-->
        <property name="exceptionAttribute" value="ex"></property>
    </bean>

html

<h1>error.html</h1>
<p th:text="${ex}"></p>
<h1>index.html</h1>
<a th:href="@{/test/hello}">测试</a>

controller

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

注解配置异常处理

@ControllerAdvice 注解:将当前类标识为异常处理的组件
@ExceptionHandler(ArithmeticException.class)注解:捕获异常和标记这方法是处理异常的。

controller

@ControllerAdvice  //将当前类标识为异常处理的组件
public class ExceptionController {
//    
    @ExceptionHandler(ArithmeticException.class)
//    ex表示控制器方法所出现的异常
    public String handleException(Throwable ex, Model model){
        model.addAttribute("ex",ex);
        return "error";
    }
}

思路

只要出现ArithmeticException.class的异常,就会通过下面的方法处理这个异常,
把异常信息共享到请求域,跳转到error 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值