feat(httpx): return 503 when a dependency is unavailable

This commit is contained in:
kk10
2026-10-06 18:45:31 +03:00
parent b540577cf9
commit d7002b4dfe
6 changed files with 44 additions and 11 deletions
+34 -1
View File
@@ -1,8 +1,14 @@
package httpx
import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"strings"
"github.com/jackc/pgx/v5/pgconn"
"mtusi2026-messenger/internal/dto"
)
@@ -23,7 +29,18 @@ func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message,
})
}
func WriteInternalError(w http.ResponseWriter, requestID string) {
func WriteInternalError(w http.ResponseWriter, requestID string, err error) {
if isUnavailable(err) {
WriteError(
w,
http.StatusServiceUnavailable,
dto.ErrorCodeUnavailable,
"dependency unavailable",
requestID,
)
return
}
WriteError(
w,
http.StatusInternalServerError,
@@ -32,3 +49,19 @@ func WriteInternalError(w http.ResponseWriter, requestID string) {
requestID,
)
}
func isUnavailable(err error) bool {
if errors.Is(err, context.DeadlineExceeded) {
return true
}
if _, ok := errors.AsType[net.Error](err); ok {
return true
}
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
return strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57P01"
}
return false
}