
API响应中简单的错误信息(例如{"error": "something went wrong."})毫无用处。有效的错误响应应该包含:问题描述、解决方法以及API的构建细节。本文介绍如何构建一个提供一致、实用且有意义的错误响应的系统。
构建可操作的错误处理系统
系统的核心是customerror结构体,它包含所有必要的错误信息。
自定义错误结构体详解:
<code class="go">type customerror struct {
baseerr error // 底层错误
statuscode int // HTTP状态码
message string // 详细错误信息
usermessage string // 用户友好的错误信息
errtype string // 错误类型
errcode string // 唯一错误代码
retryable bool // 是否可重试
metadata map[string]interface{} // 附加元数据
}</code>简而言之:
baseerr:原始错误。statuscode:HTTP状态码,例如404或500。usermessage:对用户友好的错误信息。errtype 和 errcode:用于错误分类和调试。retryable:指示是否可以重试请求。创建自定义错误
该系统包含一个工厂函数new,用于简化customerror实例的创建,确保所有错误都以一致的结构初始化:
<code class="go">func new(statuscode int, message, usermessage, errtype, errcode string, retryable bool) *customerror {
return &customerror{
baseerr: fmt.Errorf("error: %s", message),
statuscode: statuscode,
message: message,
usermessage: usermessage,
errtype: errtype,
errcode: errcode,
retryable: retryable,
metadata: make(map[string]interface{}),
}
}</code>例如,创建一个“资源未找到”错误:
<code class="go">func newNotFoundError(resource string) *customerror {
return new(
404,
fmt.Sprintf("%s not found", resource),
"请求的资源未找到。",
"not_found",
"err_not_found",
false,
)
}</code>这确保所有“未找到”错误都返回一致且有意义的响应。
newFromError函数用于将现有错误包装到自定义错误中:
<code class="go">func newFromError(err error, statuscode int, usermessage, errtype, errcode string, retryable bool) *customerror {
return &customerror{
baseerr: err,
statuscode: statuscode,
message: err.Error(),
usermessage: usermessage,
errtype: errtype,
errcode: errcode,
retryable: retryable,
metadata: make(map[string]interface{}),
}
}</code>例如,处理文件解析错误:
<code class="go">func handleParseError(filename string) *customerror {
err := parseFile(filename)
if err != nil {
return newFromError(
err,
400,
"无法处理您上传的文件。",
"bad_request",
"err_file_parse",
false,
)
}
return nil
}</code>这在提供用户友好的消息的同时保留了原始错误信息。
错误处理器:将错误转换为响应
newErrHandler函数充当内部错误和面向客户端API响应之间的转换器。其关键步骤包括:
customerror类型。apiErrorCreator接口动态创建API特定的错误响应结构体。apiError接口的fromCustomError方法将错误转换为API特定的错误。customerror类型,则返回内部服务器错误。核心逻辑:
<code class="go">func newErrHandler(creator apiErrorCreator, writerFactory func() responseWriter) func(error) {
return func(werr error) {
var customErr *customerror
writer := writerFactory()
// ... (error handling logic) ...
}
}</code>灵活的接口
错误处理器利用三个关键接口:apiError,apiErrorCreator 和 responseWriter。
apiError:定义API错误的格式。apiErrorCreator:创建新的apiError实例。responseWriter:抽象响应写入机制。工作流程
apiError和apiErrorCreator接口。responseWriter接口发送错误响应。使用YAML和模板生成错误
为了避免手动定义错误,可以使用YAML配置和Go模板来自动化此过程。
YAML配置示例:
<code class="yaml">errors:
- name: badrequest
description: 请求无效或格式错误。
err_type: bad_request
err_code: err_bad_request
err_msg: 无效请求: %s
display_msg: 请求无效。
status_code: 400
retryable: false
args:
- name: details
arg_type: string</code>Go模板将YAML配置转换为Go代码。
代码生成的优势:
预定义错误
使用代码生成机制从YAML配置动态生成预定义的错误。
总结
这个错误处理系统通过其组件的无缝协作,提供了一个强大且可扩展的解决方案。 它提供清晰、可操作且对开发人员友好的反馈,极大地简化了Go API的错误处理。
以上就是GO API中自定义错误处理系统的最终指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号