Springmvc异常捕获

CustomException 异常类

package com.xmx.config;

public class CustomException extends Exception {

    private static final long serialVersionUID = 1L;
    public String message;		  //错误信息
    public Throwable throwable;	  //Java中所有异常和错误的基类
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Throwable getThrowable() {
        return throwable;
    }
    public void setThrowable(Throwable throwable) {
        this.throwable = throwable;
    }
    public CustomException(String message) {
        super();
        this.message = message;
    }
    public CustomException(Throwable throwable) {
        super();
        this.throwable = throwable;
    }

}

CustomExceptionResolver.java

package com.xmx.config;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

public class CustomExceptionResolver implements HandlerExceptionResolver {

    //异常处理
    @ExceptionHandler(Exception.class)
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        // 解析出异常类型
        CustomException customException = null;
        String message = "";
        // 若该异常类型是系统自定义的异常,直接取出异常信息在错误页面展示即可。
        if(ex instanceof CustomException){
            customException = (CustomException)ex;
            message = customException.getMessage();
        }
        else{
            // 如果不是系统自定义异常,构造一个系统自定义的异常类型,信息为“未知错误”
            customException = new CustomException("操作错误");
            message = customException.getMessage();
        }

        //输出错误信息,便于在控制台查错
        System.out.println("发生错误了,错误信息如下:");
        System.out.println(ex);
        System.out.println();

        //错误信息
        ModelAndView modelAndView = new ModelAndView();
        //将错误信息传到页面
        modelAndView.addObject("message",message);
        //指向错误页面
        modelAndView.setViewName("error");
        return modelAndView;
    }

}

在springmvc配置文件中加入全局异常配置

 <!--全局异常配置-->
    <bean id="exceptionResolver" class="com.xmx.config.CustomExceptionResolver"></bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值