Spring Boot 错误和异常处理

发布时间 2023-05-30 12:20:48作者: ImreW

在 real time application 开发中,我们使用 Exception handling concept,以平滑终止程序。 它将 system error messages 转换为 user friendly error messages 。 但是在 Spring Boot 框架中,他们已经实现了 Exception handling concept ,这里我们需要了解 Spring Boot 框架内部如何处理 exceptions  和 Errors 。

Work flow

下图显示了 Spring Boot 中的 Error flow

在 spring / Spring boot 中使用 ErrorController 处理 errors,它将实现 BasicErrorController ,它提供了两种 methods

  1. errorHtml(): ModelAndView(从 browser 调用 trigger )
  2. error(): ResponseEntity<T> (从 non-browser/client app/postman /Any rest clients 等调用 trigger )

Work flow on Success:

Client -> Request -> DispatcherServlet -> doDispatch(req,resp) -> HandlerMapping -> Controller-> DispatcherServlet -> ViewResolver -> View -> Model (read) -> DispatcherServlet-> UI

Work flow on failure:

Client -> Request -> DispatcherServlet -> doDispatch(req,resp) -> HandlerMapping -> Controller-> DispatcherServlet -> BasicErrorController -> Response

ErrorAttributes

DefaultErrorAttributes:

BasicErrorController 将所有 error 详细信息收集为 Map<String,Object>

其中包含“ status,error, path, timestamp ...”等详细信息。此 ErrorMap 仅称为 Error Attributes ,作为对客户端的 final response 给出。

在spring boot中,如果你想自定义错误页面 white label error ,我们可以这样做。

Custom Error pages:  我们可以在“templates”文件夹下创建error.html文件,并根据需要进行设计。 这会在任何问题上执行(Http 状态:4xx 和 5xx)。 即 400,401,403,404…500,501…只执行一页即:error.html

使用 Errorcode.html(例如:404.html、500.html..)在 error folder 下创建特定的 error page 。 如果给定的 code 不匹配,它将转到 error.html。

Custom ErrorController我们可以自定义默认的 ErrorController 代码。 Spring Boot 提供了 BasicErrorController 。 如果我们为 ErrorController 定义 impl,那么 Spring boot 会选择我们的类作为priority ,并且 error.html 、 404.html 和 5xx.html 也将不起作用。

Using Error Attributes in Custom Controller:

默认情况下,Spring Boot 为 error  提供了一些 attribute ,如 timestamp, status, path , message, exception, trace..etc

  • 要在我们的 custom error controller 中使用它们,只需自动装配该 property 即可。
@Autowired
private ErrorAttributes errorAttributes;
  • 读取所有具有当前请求 value 的 properties 。
ServletWebRequest webRequest = new ServletWebRequest(req);