11人参与 • 2025-07-24 • Java
spring boot 提供了一套完善的默认异常处理机制,通过内置的 basicerrorcontroller 自动处理应用中的各类异常情况。这套机制基于 spring mvc 的异常处理框架构建,具有以下特点:
多格式响应支持:
默认错误路径:
错误页面配置:
内置异常转换:
配置选项:
实际应用示例:
// 自定义错误页 @controller public class myerrorcontroller implements errorcontroller { @requestmapping("/error") public string handleerror(httpservletrequest request) { object status = request.getattribute("javax.servlet.error.status_code"); if (status != null) { integer statuscode = integer.valueof(status.tostring()); if(statuscode == 404) { return "error/404"; } else if(statuscode == 500) { return "error/500"; } } return "error/generic"; } }
这套机制既适用于传统web应用的页面错误展示,也适配restful api的json错误响应,为开发者提供了开箱即用的异常处理解决方案。
当应用出现异常时,spring boot 会自动展示一个"whitelabel error page"(白色标签错误页),这个页面包含以下关键信息:
例如:
spring boot 会自动将常见的异常类型转换为合适的http状态码:
404 not found
nohandlerfoundexception
/api/non-existent-endpoint
400 bad request
methodargumentnotvalidexception
(方法参数验证失败)500 internal server error
开发者可以通过 application.properties
或 application.yml
文件自定义错误处理行为:
# 控制错误信息中是否包含异常消息 server.error.include-message=always # 可选值:always, on_param, never # 控制是否包含堆栈跟踪信息 server.error.include-stacktrace=on_param # 可选值:always, on_param, never # 自定义错误处理路径(默认为/error) server.error.path=/custom-error # 是否包含错误详情(绑定异常的具体字段错误) server.error.include-binding-errors=always
异常触发阶段
dispatcherservlet
捕获请求转发阶段
dispatcherservlet
将异常转发到配置的错误路径(默认是/error
)accept
头决定响应格式(html或json)错误处理阶段
basicerrorcontroller
处理该请求响应生成阶段 json响应示例:
{ "timestamp": "2023-05-15t08:12:34.567+00:00", "status": 404, "error": "not found", "path": "/api/non-existent" }
虽然spring boot提供了默认处理,但开发者可以通过以下方式扩展:
自定义errorcontroller
errorcontroller
接口geterrorpath()
和error()
方法全局异常处理器
@controlleradvice
注解定义全局异常处理类@exceptionhandler
处理特定异常@controlleradvice public class globalexceptionhandler { @exceptionhandler(value = {usernotfoundexception.class}) protected responseentity<errorresponse> handleusernotfound(usernotfoundexception ex) { errorresponse error = new errorresponse("user_not_found", ex.getmessage()); return new responseentity<>(error, httpstatus.not_found); } }
继承responseentityexceptionhandler
这套机制使得开发者可以快速构建健壮的应用程序,同时保留足够的灵活性来定制错误处理逻辑,满足特定业务场景的需求。
到此这篇关于spring boot 中的默认异常处理机制的文章就介绍到这了,更多相关spring boot 默认异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论