微服务需统一错误响应结构,采用含code、message、status、request_id字段的JSON格式;定义AppError类型及工厂方法封装错误;通过中间件统一拦截panic和AppError并转换为标准响应;集成结构化日志与错误上报。

微服务中各接口返回的错误格式必须一致,便于前端统一解析和日志系统归集。推荐使用 JSON 格式,包含状态码、错误码、错误信息和可选的请求 ID:
Go 中可定义如下结构体:
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Status int `json:"status"`
RequestID string `json:"request_id,omitempty"`
}避免直接使用 errors.New 或 fmt.Errorf,而是构建可携带错误码和 HTTP 状态的错误类型:
type AppError struct {
Code int
Message string
Status int
}
func (e *AppError) Error() string {
return e.Message
}
// 工厂函数示例
func NewBadRequest(code int, msg string) *AppError {
return &AppError{Code: code, Message: msg, Status: http.StatusBadRequest}
}
func NewInternalError(code int, msg string) *AppError {
return &AppError{Code: code, Message: msg, Status: http.StatusInternalServerError}
}将常用错误预定义为常量,提高可读性和复用性:
立即学习“go语言免费学习笔记(深入)”;
const (
ErrInvalidParam = iota + 1000
ErrUserNotFound
ErrDBConnection
)
var (
ErrInvalidParamError = NewBadRequest(ErrInvalidParam, "请求参数不合法")
ErrUserNotFoundError = NewBadRequest(ErrUserNotFound, "用户不存在")
)在 Gin / Echo / Fiber 等框架中,通过中间件捕获 handler 中 panic 或显式返回的 *AppError,并统一渲染响应:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
193
Gin 示例中间件:
func ErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: 5000,
Message: "服务内部异常",
Status: http.StatusInternalServerError,
RequestID: c.GetString("request_id"),
})
return
}
}()
c.Next()
if len(c.Errors) > 0 {
appErr, ok := c.Errors.Last().Err.(*AppError)
if ok {
c.JSON(appErr.Status, ErrorResponse{
Code: appErr.Code,
Message: appErr.Message,
Status: appErr.Status,
RequestID: c.GetString("request_id"),
})
c.Abort()
return
}
}
}
}注册时注意顺序:先注入请求 ID 中间件,再注册错误处理中间件。
在错误中间件中,记录结构化日志(含 error stack、request_id、path、method);对特定错误码(如 DB、RPC 调用失败)触发告警或上报至 Sentry / Prometheus:
例如:
slog.Error("app error occurred",
"request_id", c.GetString("request_id"),
"path", c.Request.URL.Path,
"error_code", appErr.Code,
"error_msg", appErr.Message,
"stack", debug.Stack())以上就是如何在Golang中实现微服务统一异常处理_标准化错误返回的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号