Spring Boot-配置全局的异常捕获配置全局的异常捕获
汇总目录链接:Spring Boot开发常用技术博客目录
本文只是配置一个简单的全局的异常捕获,如有需要可以根据实际情况开发其它异常和自定义的异常。
web页面跳转页面跳转
项目结构如下:
MyExceptionHandler.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class MyExceptionHandler {
private static final String MY_ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace();
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(MY_ERROR_VIEW);
return mav;
}
}
error.html
发生错误:发生错误:
异常测试类 ErrorController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 异常测试类
*/
@Controller
@RequestMapping(value = "err")
public class ErrorController {
@RequestMapping(value = "/error")
String error() {
int a = 1 / 0;
return "aaa";
}
}
执行效果:
评论0