package middleware import ( "context" "errors" apierrors "git.yuntuo.hk/k2safe/go-omni/errors" "git.yuntuo.hk/k2safe/go-omni/httpx" ) // ContextErrors classifies unhandled context errors using project catalog keys. // Empty keys leave that class unchanged. Explicit API errors always take // precedence, even if they wrap a context failure. Causes stay available to logs. func ContextErrors(canceledKey, deadlineKey string) httpx.Middleware { return func(next httpx.Handler) httpx.Handler { return func(c *httpx.Context) error { err := next(c) var public *apierrors.APIError if err == nil || errors.As(err, &public) { return err } if canceledKey != "" && errors.Is(err, context.Canceled) { return apierrors.ByCode(canceledKey).WithCause(err) } if deadlineKey != "" && errors.Is(err, context.DeadlineExceeded) { return apierrors.ByCode(deadlineKey).WithCause(err) } return err } } }