SpringMVC之处理异常

SpringMVC之处理异常

1.编写自定义异常类

功能:

做提示信息

public class SysException extends Exception {

    /**
     * 存储提示信息
     */
    private String message;

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

    public void setMessage(String message) {
        this.message = message;
    }


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

2.编写异常处理器

public class SysExceptionResolver implements HandlerExceptionResolver {


    /**
     * 处理异常的业务逻辑
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //获取到异常对象
        SysException sysException = null;
        if (e instanceof SysException){
            sysException = (SysException)e;
        }else{
            sysException = new SysException("系统正在维护");
        }
        //创建ModelAndView对象。
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMsg",sysException.getMessage());
        modelAndView.setViewName("error");//error.jsp在 /WEB-INF/pages/ 路径下
        return modelAndView;
    }
}

3.配置异常处理器

跳转到提示页面

springmvc.xml中

<!--配置异常处理器-->
<bean class="xyz.zhouzhousag.exception.SysExceptionResolver" id="sysExceptionResolver">

</bean>

4.测试Controller

controller

@Controller
@RequestMapping("/user")
public class userControll {
    @RequestMapping("/testException")
    public String testException() throws SysException {
        System.out.println("testException执行了。。。。");
        try {
            //模拟异常
            int i = 1/0;
        } catch (Exception e) {
            //控制台打印异常信息
            e.printStackTrace();
            //抛出自定义异常信息
            throw new SysException("查询所有用户异常");
        }

        return "success";
    }
}

jsp

<a href="user/testException">异常处理</a>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值