首页 > 编程语言 > 详细

springmvc异常处理器

时间:2018-05-04 10:01:38      阅读:206      评论:0      收藏:0      [点我收藏+]
//编写自定义异常类
package cn.bdqn.stusystem.util;

public class MyException extends Exception{

    private String message;

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

    public MyException() {
    }

    public String getMessage() {
        return message;
    }

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

//实现异常处理器
package cn.bdqn.stusystem.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

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

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

public class MyHandleException implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception arg3) {
        // 定义异常信息
                String msg;

                // 判断异常类型
                if(arg3 instanceof MyException){
                    msg = arg3.getMessage();
                }else{
                    Writer writer = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(writer);
                    arg3.printStackTrace(printWriter);
                    msg = writer.toString();
                }
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("msg", msg);
            modelAndView.setViewName("error");
            return modelAndView;
    }

}

//在springmvc中配置异常处理器
<bean id="myHandleException" class="cn.bdqn.stusystem.util.MyHandleException"></bean>

 

springmvc异常处理器

原文:https://www.cnblogs.com/ZhangHaiBK/p/8988699.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!