From 97276ef5440d5276de9d6c60bc1775dad09d85d4 Mon Sep 17 00:00:00 2001 From: Lynwee <1507509064@qq.com> Date: Wed, 18 Sep 2024 13:40:14 +0800 Subject: [PATCH] fix(utils): add new function ApiOutputAdvancedErrorWithCustomCode (#8063) --- backend/server/api/shared/api_output.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/backend/server/api/shared/api_output.go b/backend/server/api/shared/api_output.go index debbe0a0e76..b213f91e963 100644 --- a/backend/server/api/shared/api_output.go +++ b/backend/server/api/shared/api_output.go @@ -67,6 +67,28 @@ func ApiOutputErrorWithCustomCode(c *gin.Context, code int, err error) { c.Writer.Header().Set("Content-Type", "application/json") } +// ApiOutputAdvancedErrorWithCustomCode writes a JSON error message to the HTTP response body +func ApiOutputAdvancedErrorWithCustomCode(c *gin.Context, httpStatusCode, customBusinessCode int, err error) { + if e, ok := err.(errors.Error); ok { + logruslog.Global.Error(err, "HTTP %d error", e.GetType().GetHttpCode()) + messages := e.Messages() + c.JSON(e.GetType().GetHttpCode(), &ApiBody{ + Success: false, + Message: e.Error(), + Code: customBusinessCode, + Causes: messages.Causes(), + }) + } else { + logruslog.Global.Error(err, "HTTP %d error (native)", http.StatusInternalServerError) + c.JSON(httpStatusCode, &ApiBody{ + Success: false, + Code: customBusinessCode, + Message: err.Error(), + }) + } + c.Writer.Header().Set("Content-Type", "application/json") +} + // ApiOutputError writes a JSON error message to the HTTP response body func ApiOutputError(c *gin.Context, err error) { if e, ok := err.(errors.Error); ok {