SpringBoot入门学习(十四)~~统一错误处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaozhegaa/article/details/82912574

目录

 

SpringBoot统一错误处理

一、入门案例

二、编写统一异常处理类

三、编写的异常页面


SpringBoot统一错误处理

       之前在Web.xml中,我们可以通过配置<error-page/>的配置去指定我们的404页面、500页面,也可以写统一异常处理类继承HanlerExceptionResolver类,对异常统一管理。而在SpringBoot中,则更加简单,提供了相应的解决方法。

  • 一、入门案例

1、写一个简单的hello程序,返回hello,但是在返回值之前,发生除0错误

@Controller
public class FreeMarkerController {
  
@RequestMapping("/hello")
  
@ResponseBody
  
public String helloPage(Model model){
     
int i = 10/ 0;
     
return "hello";
   }
}

2、启动项目,访问/hello查看效果:

会报/by zero错误,这是正常的。但是对于上线的服务来说,这是不友好的提醒。

  • 二、编写统一异常处理类

  1. 写一个ErrorControllerAdvice类,该类打上@ControllerAdvice注解,@ControllerAdvice表示对Controller增强,具有异常处理的功能。
  2. 编写一个异常处理的方法,方法上面打上:
@ExceptionHandler(Exception.class)
因为这个ControllerAdvice也是一个控制器类,形参需要什么可以自己加。这里简单把异常输出,然后跳转到:自定义的某个页面
@ControllerAdvice

  public class ErrorControllerAdvice {

   @ExceptionHandler(Exception.class)

   public String hanlererException(Exception exception, HandlerMethod method,Model model){

      System.out.println("统一异常处理");

      System.out.println("把异常信息写入数据库");

      System.out.println(exception.getMessage());

      System.out.println(method.getBean().getClass());

      System.out.println(method.getMethod().getName());

      System.out.println("把异常写入数据库成功");

      model.addAttribute("errorMessage","这里显示我后台的错误信息");

      return "myError";

  

   }

}
 
<body>

    你自定义处理的异常为:${errorMessage}

  </body>

3、启动项目,尝试访问

效果图如下:

 

说明统一异常处理配置就可以了。

  • 三、编写的异常页面

  1. SpringBoot默认情况下,把所有的错误都重新定位到了/error这个处理路径上,有BasicErrorController类完成处理
  2. SpringBoot提供了默认的替换错误页面的路径

静态错误页面默认结构

  1. resources/
    1. public/
      1. 404.html
      2. 401.html
      3. 500.html
      4. 5xx.html

也可以使用模板页面

  1. resources/
    1. templates/
      1. 404.ftl
      2. 401. ftl
      3. 500. ftl
      4. 5xx. Ftl

效果图如下:

 

【注意:】值得注意的一点就是:如果我配置了异常处理类之后呢,那么默认也就不在走500.html,而是交由我们的异常处理类管理,如果想返回到500.html,直接在异常处理类中return “500”即可。

猜你喜欢

转载自blog.csdn.net/xiaozhegaa/article/details/82912574
今日推荐