spring mvc 全局异常处理
package com.tool; public class MyException extends Exception{ public String Msg; public String ErrCode; public MyException(String msg,String code) { super(msg); Msg=msg; ErrCode=code; } }
package com.tool; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class MyExceptionHandler implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Map<String, Object> model = new HashMap<String, Object>(); model.put("ex", ex.getMessage()); // 这里可根据不同错误转向不同页面 if (ex instanceof MyException) { return new ModelAndView("error", model); } else { return new ModelAndView("error", model); } } }
<bean id="exceptionResolver" class="com.tool.MyExceptionHandler" />