1. 程式人生 > >springmvc異常處理器

springmvc異常處理器

rac javax .get name ava exce instance exceptio trac

//編寫自定義異常類
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異常處理器