SprringMVC之异常处理
自定义异常类
public class CustomException extends Exception {
public CustomException() {
super();
}
public CustomException(String message) {
super(message);
}
}
自定义异常处理类
public class HandlerCustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
CustomException customException;
if (e instanceof CustomException) {
customException = (CustomException) e;
} else {
customException = new CustomException("系统错误,请与管理员联系");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", customException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
错误JSP页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Error</title>
</head>
<body>
${message}
</body>
</html>
将异常处理类加入SpringMVC配置文件中
<bean class="com.ttpfx.library.HandlerCustomExceptionResolver"/>
Controller、Service、Dao等处,直接抛出异常即可。