Spring Boot 错误和异常处理
在 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
- errorHtml(): ModelAndView(从 browser 调用 trigger )
- 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了