SpringBoot 中异常处理
SpringBoot 中对于异常处理提供了五种处理方式
五种处理方式顺序:
- 局部的异常处理
- 全局的异常处理
- 实现 HandlerExceptionResolver 接口的异常处理
- 返回 SimpleMappingExceptionResolver 对象的异常处理
- 自定义 error 页面
1 自定义错误页面
SpringBoot 默认的处理异常的机制:
SpringBoot默认的已经提供了一套处理异常的机制。 一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 SpringBoot 中提供了一个名为 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息。
如果我们需要将所有的异常统一跳转到自定义的错误页面,需要再src/main/resources/templates 目录下创建 error.html 页面。注意:页面名称必须叫 error
1.1 处理代码
@RequestMapping("/index")
public String index(){
String str=null;
int length = str.length();
return "ok";
}
1.2 处理视图
1.3 处理结果
2 局部处理:使用@ExceptionHandler 注解
2.1 处理代码
@RequestMapping("/index")
public String index(){
String str=null;
int length = str.length();
return "ok";
}
@RequestMapping("/byZero")
public String byZero(){
int i=10/0;
return "ok";
}
@ExceptionHandler(value = {java.lang.NullPointerException.class,java.lang.ArithmeticException.class})
public ModelAndView handlerNullException(Exception e){
ModelAndView view = new ModelAndView();
view.setViewName("smallError");
view.addObject("smallError",e.toString());
return view;
}
2.2 处理视图
2.3 处理结果
3 全局处理:使用@ExceptionHandler 加@ControllerAdvice 注解
3.1 处理代码
/**
* @author 守鹤
* @date 2020/5/14 0:06
*/
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(value = {java.lang.NullPointerException.class})
public ModelAndView globalNullPoint(Exception e){
ModelAndView view = new ModelAndView();
view.setViewName("globalError");
view.addObject("globalError",e.toString());
return view;
}
}
3.2 处理视图
3.3 处理结果
4 自定义处理:使用SimpleMappingExceptionResolver 对象
4.1 处理代码
@Configuration
public class GlobalSimpleMappingException {
@Bean
//此方法返回值必须是 SimpleMappingExceptionResolver 对象
public SimpleMappingExceptionResolver getSimpleException(){
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
/**
* 参数一:异常类型,并且是全名
* 参数二:视图名称
* */
* properties.setProperty("java.lang.NullPointerException","simpleNullError");
properties.setProperty("java.lang.ArithmeticException","simpleArithmeError");
resolver.setExceptionMappings(properties);
return resolver;
}
}
4.2 处理视图
4.3 处理结果
5 自定义处理:实现HandlerExceptionResolver接口
5.1 处理代码
/**
* @author 守鹤
* @date 2020/5/14 20:46
*/
@Configuration
public class MyExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if(e instanceof NullPointerException){
modelAndView.setViewName("MyNullError");
}
if(e instanceof ArithmeticException){
modelAndView.setViewName("MyArithmeError");
}
modelAndView.addObject("myError",e.toString());
return modelAndView;
}
}
5.2 处理视图
5.3 处理结果
SpringBoot 5种异常处理机制 demo
链接:https://pan.baidu.com/s/1J3a5jgeVLNFxlu3JPjehtA
提取码:3moc