Не показывать клиенту контекст обёртки ошибок
This commit is contained in:
@@ -319,8 +319,10 @@ func TestUnavailableCauseIsLoggedButNotReturned(t *testing.T) {
|
||||
})
|
||||
rec, eb := do(t, e, http.MethodGet, "/down", "", nil)
|
||||
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
|
||||
if strings.Contains(rec.Body.String(), "connection refused") {
|
||||
t.Fatalf("cause leaked to the client: %s", rec.Body.String())
|
||||
// Neither the cause nor the wrapping context of internal operations
|
||||
// ("select user: ...") may reach the client.
|
||||
if eb.Error.Message != "database unavailable" {
|
||||
t.Fatalf("client message = %q, want only the application message", eb.Error.Message)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "connection refused") || !strings.Contains(logs.String(), eb.Error.RequestID) {
|
||||
t.Fatalf("log must carry the cause and the request id, got:\n%s", logs.String())
|
||||
|
||||
@@ -53,11 +53,17 @@ func Fail(c *gin.Context, status int, code, message string) {
|
||||
|
||||
// Error maps an application error to its status. Anything that is not an
|
||||
// application error is logged with its text and reported as an opaque 500,
|
||||
// so internal details never reach the client. A known error answered with a
|
||||
// 5xx (a dependency outage) shows the client only its safe message, and its
|
||||
// cause goes to the log for the operator.
|
||||
// so internal details never reach the client. An application error shows the
|
||||
// client only its own message, never the context it was wrapped in on the
|
||||
// way up; when it is answered with a 5xx (a dependency outage) the full
|
||||
// chain and the cause go to the log for the operator.
|
||||
func Error(c *gin.Context, err error) {
|
||||
mapped, known := kinds[apperr.KindOf(err)]
|
||||
appErr, isApp := errors.AsType[*apperr.Error](err)
|
||||
var mapped statusCode
|
||||
known := false
|
||||
if isApp {
|
||||
mapped, known = kinds[appErr.Kind]
|
||||
}
|
||||
if !known {
|
||||
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
|
||||
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
@@ -65,12 +71,12 @@ func Error(c *gin.Context, err error) {
|
||||
}
|
||||
if mapped.status >= http.StatusInternalServerError {
|
||||
attrs := []any{"request_id", RequestID(c), "error", err.Error()}
|
||||
if e, ok := errors.AsType[*apperr.Error](err); ok && e.Cause != nil {
|
||||
attrs = append(attrs, "cause", e.Cause.Error())
|
||||
if appErr.Cause != nil {
|
||||
attrs = append(attrs, "cause", appErr.Cause.Error())
|
||||
}
|
||||
logger(c).Error("request failed", attrs...)
|
||||
}
|
||||
Fail(c, mapped.status, mapped.code, err.Error())
|
||||
Fail(c, mapped.status, mapped.code, appErr.Message)
|
||||
}
|
||||
|
||||
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
|
||||
|
||||
Reference in New Issue
Block a user