SpringMVC之配置异常处理器

本文详细介绍了在Spring MVC框架中如何进行异常处理,包括自定义异常类、异常处理器及在配置文件中的设置。通过示例代码,展示了如何捕获并处理业务逻辑中可能出现的异常,确保应用程序的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1.模拟异常访问

@Controller
@RequestMapping("/test")
public class ExceptionTest {
    @RequestMapping("/1")
    public String test1() throws SysException{
        try {
            System.out.println(1/0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException("除数为零");
        }
        return "success";
    }
}

 

2.自定义异常类

public class SysException extends Exception{
    private String message;

    public SysException(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

}

3.自定义异常处理器(实现HandlerExceptionResolver)

public class SysExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof SysException){
            e = (SysException) e;
        }else {
            e = new SysException("该项功能正在维护中...");
        }
        ModelAndView view = new ModelAndView();
        view.addObject("errorMsg",e.getMessage());
        view.setViewName("error");
        return view;
    }
}

4.在spring配置文件中添加异常处理器的bean

<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/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="cn.source"></context:component-scan>
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="sysException" class="cn.source.exception.SysExceptionResolver"></bean>
    <mvc:annotation-driven/>
</beans>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值