对异常处理的思路
系统中异常包括两类:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理
SpringMVC异常处理
- 自定义异常类
package com.bamzhy.exception;
public class CustomException extends Exception {
public static final long serialVersionUID=1L;
//
public CustomException(String message) {
super(message);
this.message = message;
}
//异常信息
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- 自定义异常视图解析器
package com.bamzhy.exception;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
CustomException customException=null;
//如果抛出的是系统自定义异常则直接转换
if (e instanceof CustomException){
customException=(CustomException)e;
}else{
//如果抛出的不是系统自定的异常则重新构造一个系统错误异常
customException=new CustomException("跟管理员联系也没用把电脑关了吧");
}
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("message",customException.getMessage());
System.out.println(customException.getMessage());
//设定好要跳转到的页面
modelAndView.setViewName("/WEB-INF/error.jsp");
return modelAndView;
}
- 自定义异常视图页面
package com.bamzhy.Controller;
import com.bamzhy.bean.User;
import com.bamzhy.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ErrorController {
@RequestMapping("/haha12345")
public void test() throws CustomException{
if (true){
throw new CustomException("用户名不存在!");
}
}
}
- 测试+结果
输入:http://localhost:8080/haha12345
结果:
值得一提的一个小bug
- 当我配置了FreeMarker的view解析器时,你重定向.jsp文件,spring会报
javax.servlet.ServletException: Could not resolve view with name ‘/WEB-INF/error.jsp’ in servlet with name ‘springmvcservlet’ - 这个说明了spring是需要view解析器的,如果你自己定义了不让他用默认的,但是自己定义的又用不了他就会告诉你这个url他没办法给你解析。(其实是DispatcherServlet不知道给哪个view解析器)
这个bug真折腾人。