在Spring MVC中我们可以通过以下2中途径来对异常进行集中处理:
一.继承HandlerExceptionResolver接口实现自己的处理方法,如:
复制代码
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//添加自己的异常处理逻辑,如日志记录等
// TODO Auto-generated method stub
return new ModelAndView("exception");
}
}
复制代码
然后在项目的配置文件中添加:
这样就完成了异常的捕捉和处理。
二.我们介绍了第一种捕捉处理异常方式,但是第一种方式需要在配置文件中进行配置,有的时候我们会觉得配置文件内容太多太乱,那么我们就可以借助@ExceptionHandler注解来实现零配置的异常捕捉和处理。
首先,在我们项目的包com.demo.web.controllers中为controller建立一个父类BaseController,内容如下:
复制代码
package com.demo.web.controllers;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
public abstract class BaseController {
@ExceptionHandler
public String exception(HttpServletRequest request, Exception e) {
//添加自己的异常处理逻辑,如日志记录
request.setAttribute("exceptionMessage", e.getMessage());
// 根据不同的异常类型进行不同处理
if(e instanceof SQLException)
return "testerror";
else
return "error";
}
}
复制代码
其次,修改项目中HelloWorldController让它继承于BaseController以便进行测试:
public class HelloWorldController extends BaseController{
//...内容省略
}
然后,修改HelloWorldController 中的index方法,使其抛出异常,看能不能正常捕捉:
复制代码
//@AuthPassport
@RequestMapping(value={"/index","/hello"})
public ModelAndView index() throws SQLException{
throw new SQLException("
数据库异常。");
/*ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", "Hello World!");
modelAndView.setViewName("index");
return modelAndView;*/
}
复制代码
最后,在views文件夹中添加testerror.
jsp视图来显示错误信息:
复制代码
<%@ page language="java" contentType="text/
html; charset=UTF-8"
pageEncoding="UTF-8"%>
${exceptionMessage}