springmvc——全局异常处理和编写自定义异常

springmvc的全局异常处理
  • springmvc对于异常处理给我们留有一个处理异常的接口HandlerExceptionResolver,具体接口如下边的代码:
package org.springframework.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface HandlerExceptionResolver {
    ModelAndView resolveException(HttpServletRequest var1, HttpServletResponse var2, Object var3, Exception var4);
}

仔细观察这个接口, 我们发现这个接口返回类型是ModelAndView,也就是说当出现异常时,我们可以以一个界面来展现给用户,让我们的网站设计的更加友好。 现在我们通过编写具体的实现类

package com.hy.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Han Yu
 * @Description:
 * @Date: Create in 13:24 2019/2/23
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String result = "发生异常请联系管理员";

        if(e instanceof CustomDemoException){
            result = ((CustomDemoException)e).getErroeMsg();
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("result",result);
        modelAndView.setViewName("error/error");
        return modelAndView;
    }
}

上面这段代码仔细阅读可以发现一个CustomDemoException类,这个类的作用呢就是我们的自定义异常,我们可以对于无法用原来的异常处理的异常编写自定义异常处理类,而且可以编写多个,这里编写了一个作为列子

package com.hy.exception;

/**
 * @Author: Han Yu
 * @Description:
 * @Date: Create in 13:39 2019/2/23
 */
public class CustomDemoException extends Exception {
    private String erroeMsg;

    public CustomDemoException(){
        super();

    }
    public CustomDemoException(String erroeMsg) {
        super();
        this.erroeMsg = erroeMsg;
    }

    public String getErroeMsg() {
        return erroeMsg;
    }

    public void setErroeMsg(String erroeMsg) {
        this.erroeMsg = erroeMsg;
    }
}

  • 我们现在编写了类实现了异常的接口,还编写了自定义异常类,但是总感觉还缺少点什么,springmvc如何知道我们定义的异常类呢,?

最重要的一步,我们需要在springmvc.xml配置文件中写一个bean,这个bean就是springmvc给我们提供的HandlerExceptionResolver接口的实现类

    <!--异常处理  全局异常  一个系统就一个-->
    <!--配置全局异常处理器-->
    <bean class="com.hy.exception.CustomExceptionResolver"/>

这样springmvc就可以加载这个类,判断他是实现的接口而知道这是一个全局异常处理器。

  • 测试
 @RequestMapping("/index")
    public String fmdIndex() throws Exception{
//        int i=1/0;

        if(true){
            throw new CustomDemoException("你好 自定义异常");
        }

        return "Login/Index";
    }

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值