答案是:在Golang中实现REST API错误返回需定义统一的ErrorResponse结构体,包含Error、Message和Code字段,使用sendErrorResponse辅助函数设置Content-Type、状态码并返回JSON;根据错误类型返回400、401、403、404、422或500等恰当状态码,避免一律返回500;可定义AppError自定义错误类型携带错误信息与状态码,在handler中判断类型并响应,确保前端获得结构一致、语义清晰的错误信息。

在Golang中实现REST API错误返回,关键在于统一格式、明确状态码、提供可读的错误信息,并与HTTP响应良好集成。以下是一些实用的做法和结构示例。
前端通常希望所有错误都以一致的JSON结构返回。可以定义一个通用的错误响应结构体:
type ErrorResponse struct {
Error string `json:"error"`
Message string `json:"message,omitempty"`
Code int `json:"code,omitempty"`
}
这样无论发生什么错误,返回的JSON结构都保持一致,便于前端处理。
写一个工具函数来封装错误响应的发送逻辑,避免重复代码:
立即学习“go语言免费学习笔记(深入)”;
func sendErrorResponse(w http.ResponseWriter, message string, statusCode int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(ErrorResponse{
Error: http.StatusText(statusCode),
Message: message,
Code: statusCode,
})
}
在处理函数中可以直接调用:
if user, err := getUser(id); err != nil {
sendErrorResponse(w, "用户不存在", http.StatusNotFound)
return
}
不要把所有错误都返回500。根据错误类型设置合适的HTTP状态码:
例如参数校验失败时:
if email == "" {
sendErrorResponse(w, "邮箱不能为空", http.StatusBadRequest)
return
}
可以定义应用级错误类型,携带更多信息:
type AppError struct {
Err error
Msg string
Status int
}
func (e *AppError) Error() string {
return e.Err.Error()
}
在业务逻辑中返回这种错误,然后在handler中判断类型并处理:
if err != nil {
if appErr, ok := err.(*AppError); ok {
sendErrorResponse(w, appErr.Msg, appErr.Status)
} else {
sendErrorResponse(w, "服务器内部错误", http.StatusInternalServerError)
}
return
}
以上就是如何在Golang中实现REST API错误返回的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号