异常处理
配置文件添加异常处理器
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp"/> </bean>
添加自定义异常类
package com.oylong.Exception; public class IException extends Exception { private String msg; public IException(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
添加自定义异常处理器
package com.oylong.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 IExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { IException iException = null; if (e instanceof IException) { iException = (IException) e; } else { iException = new IException("未知的错误"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errorMsg", iException.getMsg()); return modelAndView; } }
配置文件中添加bean
<bean id="iExceptionResolver" class="com.oylong.Exception.IExceptionResolver"></bean>
- 运行时抛出
IException
即可