答案是:在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状态码:
- 400 Bad Request:请求参数无效
- 401 Unauthorized:未登录
- 403 Forbidden:权限不足
- 404 Not Found:资源不存在
- 422 Unprocessable Entity:数据验证失败
- 500 Internal Server Error:服务器内部错误
例如参数校验失败时:
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
}
基本上就这些。核心是结构统一、状态码准确、信息清晰。不复杂但容易忽略细节。










