Spring MVC 异常处理

异常处理实现方法:
1. 自定义一个异常类 extends Exception
2. 定义一个异常错误的jsp页面,例如:505.jsp
3. 自定义一个全局异常类实现接口HandlerExceptionResolver
重载函数resolveException
实现逻辑:
a. 当异常为自定义异常的时候,把消息设置到自定义的异常类的消息中
b.当异常非自定义异常的时候,则构造一个自定义的异常类型
c.跳转到错误页面
4. 配置Spring MVC配置文件中使用自定义的全局类

<beanclass="cn.itcast.ssm.exception.CustomHandlerExceptionResolver"/>

自定义异常类

package cn.itcast.ssm.exception;

public class CustomException extends  Exception {


    private  String message;

    public  CustomException(String message){
        super(message);
        this.message = message;
    }

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

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

自定义全局异常处理类

package cn.itcast.ssm.exception;

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

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

public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        /*
           解析出异常类型
           如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示
           如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
        }*/

        CustomException customException = null;
        if( ex instanceof CustomException){
            customException = (CustomException)ex;
        }else{
            customException = new CustomException("位置的错误:"+ex.getMessage());
        }

        //错误信息
        String errorMsg = customException.getMessage();

        ModelAndView modelAndView= new ModelAndView();

        modelAndView.addObject("message", errorMsg);
        modelAndView.setViewName("500");

        return  modelAndView;

    }
}

500.jsp页面

<%--
  Created by IntelliJ IDEA.
  User: duoduo
  Date: 2017/3/26
  Time: 10:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Error Msg</title>
</head>
<body>
${message}
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值