diff --git a/projects/kit/docs/auth-http.md b/projects/kit/docs/auth-http.md index c17e6822..ff99a844 100644 --- a/projects/kit/docs/auth-http.md +++ b/projects/kit/docs/auth-http.md @@ -93,3 +93,24 @@ export const appConfig: ApplicationConfig = { Automatic retry is limited to `GET`, `HEAD`, `OPTIONS`, or requests carrying an `Idempotency-Key`. Ordinary writes are never retried automatically. Retries cover transient statuses `0`, `408`, `429`, `502`, `503`, and `504`, and honor `Retry-After`. When offline support is enabled, register `offlineInterceptor` before `kitAuthInterceptor`. Local mode then prevents credential generation and network transport while allowing a matched read policy to serve the scoped replica. + +### Request-owned error notifications + +`onServerError` receives the server body message for HTTP 400, 409, 422, and 500. +For requests whose caller displays its own error UI, set the public boolean context token +`KIT_SKIP_ERROR_NOTIFICATIONS` (default `false`): + +```ts +import { HttpContext } from '@angular/common/http'; +import { KIT_SKIP_ERROR_NOTIFICATIONS } from '@rdlabo/ionic-angular-kit'; + +http.post('/applications', payload, { + context: new HttpContext().set(KIT_SKIP_ERROR_NOTIFICATIONS, true), +}); +``` + +This suppresses only response-error notification hooks: `onUnauthorized`, `onForbidden`, +`onNetworkError`, `onRateLimited`, `onMaintenance`, `onServerBusy`, and `onServerError`. +The original error still rejects to the caller. It does not bypass authentication, stop +401 recovery/replay, change retry or offline-fallback behavior, prevent access revocation +(`onAuthAccessDenial`), or suppress auth-header failures (`onAuthError`). diff --git a/projects/kit/src/lib/http/kit-http.interceptor.spec.ts b/projects/kit/src/lib/http/kit-http.interceptor.spec.ts index 737aa069..1bbf31bc 100644 --- a/projects/kit/src/lib/http/kit-http.interceptor.spec.ts +++ b/projects/kit/src/lib/http/kit-http.interceptor.spec.ts @@ -5,7 +5,13 @@ import { Observable } from 'rxjs'; import { of, throwError } from 'rxjs'; import { firstValueFrom } from 'rxjs'; -import { KIT_AUTH_BOOTSTRAP_REQUEST, kitAuthInterceptor, provideKitHttp, type KitHttpConfig } from './kit-http.interceptor'; +import { + KIT_SKIP_ERROR_NOTIFICATIONS, + KIT_AUTH_BOOTSTRAP_REQUEST, + kitAuthInterceptor, + provideKitHttp, + type KitHttpConfig, +} from './kit-http.interceptor'; import { KitAuthAccessService } from '../auth/auth-access.service'; import { isIdentityAuthFailure } from './auth-failure'; @@ -62,6 +68,54 @@ describe('kitAuthInterceptor', () => { TestBed.resetTestingModule(); }); + it.each([false, true])('409 preserves the error and only notifies when suppression is %s', async (skip) => { + const config = makeConfig(); + setupInterceptor(config); + const req = baseReq.clone({ context: new HttpContext().set(KIT_SKIP_ERROR_NOTIFICATIONS, skip) }); + const error = new HttpErrorResponse({ status: 409, error: { message: 'Already applied' } }); + const next = vi.fn(() => throwError(() => error)); + await expect(firstValueFrom(runInterceptor(req, next))).rejects.toBe(error); + expect(next).toHaveBeenCalledTimes(1); + expect(config.onServerError).toHaveBeenCalledTimes(skip ? 0 : 1); + if (!skip) expect(config.onServerError).toHaveBeenCalledWith('Already applied'); + }); + + it.each([401, 403, 0, 429, 503, 502, 400, 422, 500])('suppresses notification hooks for %s and preserves rejection', async (status) => { + const config = makeConfig({ onRateLimited: vi.fn(), onMaintenance: vi.fn(), onServerBusy: vi.fn() }); + setupInterceptor(config); + const req = new HttpRequest('POST', '/api/test', {}, { context: new HttpContext().set(KIT_SKIP_ERROR_NOTIFICATIONS, true) }); + const error = new HttpErrorResponse({ status, error: { message: 'Failure' } }); + await expect(firstValueFrom(runInterceptor(req, () => throwError(() => error)))).rejects.toBe(error); + for (const hook of [ + config.onUnauthorized, + config.onForbidden, + config.onNetworkError, + config.onRateLimited, + config.onMaintenance, + config.onServerBusy, + config.onServerError, + ]) { + expect(hook).not.toHaveBeenCalled(); + } + }); + + it('keeps 401 recovery and authenticated replay when notifications are suppressed', async () => { + const config = makeConfig({ recoverAuthAccess: vi.fn().mockResolvedValue(true) }); + setupInterceptor(config); + const req = baseReq.clone({ context: new HttpContext().set(KIT_SKIP_ERROR_NOTIFICATIONS, true) }); + const error = new HttpErrorResponse({ status: 401 }); + const response = new HttpResponse({ body: 'recovered' }); + const next = vi + .fn() + .mockReturnValueOnce(throwError(() => error)) + .mockReturnValueOnce(of(response)); + await expect(firstValueFrom(runInterceptor(req, next))).resolves.toBe(response); + expect(config.recoverAuthAccess).toHaveBeenCalledTimes(1); + expect(next).toHaveBeenCalledTimes(2); + expect(config.getAuthHeaders).toHaveBeenCalledTimes(2); + expect(config.onUnauthorized).not.toHaveBeenCalled(); + }); + // Every hook except getAuthHeaders is optional; a config that only provides // getAuthHeaders must drive the pipeline without throwing on the missing hooks. describe('optional hooks (only getAuthHeaders provided)', () => { diff --git a/projects/kit/src/lib/http/kit-http.interceptor.ts b/projects/kit/src/lib/http/kit-http.interceptor.ts index c5359d18..bc97c453 100644 --- a/projects/kit/src/lib/http/kit-http.interceptor.ts +++ b/projects/kit/src/lib/http/kit-http.interceptor.ts @@ -20,6 +20,13 @@ import { isExplicitAuthDenial, KitAuthAccessService } from '../auth/auth-access. */ export const KIT_AUTH_BOOTSTRAP_REQUEST = new HttpContextToken(() => false); +/** + * Suppresses response-error notification hooks for requests whose caller owns the error UI. + * Defaults to false. Errors still propagate unchanged; authentication recovery/replay, + * access revocation, auth-header failure hooks, retries, and offline fallback remain active. + */ +export const KIT_SKIP_ERROR_NOTIFICATIONS = new HttpContextToken(() => false); + /** * Marks an auth-recovery replay so {@link KitHttpConfig.recoverAuthAccess} is not invoked again. * @@ -258,7 +265,7 @@ export interface KitHttpConfig { */ onRateLimited?(retryAfterSeconds?: number): void; /** - * UX hook for `400` / `422` / `500` responses that carry a server-provided message. + * UX hook for `400` / `409` / `422` / `500` responses that carry a server-provided message. * * @remarks * Optional; defaults to a no-op. Note that the message comes straight from the API; prefer a @@ -446,6 +453,8 @@ const handleTransportError = ( * @internal */ const dispatchError = (config: KitHttpConfig, req: HttpRequest, error: HttpErrorResponse): void => { + if (req.context.get(KIT_SKIP_ERROR_NOTIFICATIONS)) return; + const status = error.status; const retryAfterMs = parseRetryAfterMs(error); const retryAfterSeconds = retryAfterMs === null ? undefined : Math.round(retryAfterMs / 1000); @@ -468,7 +477,7 @@ const dispatchError = (config: KitHttpConfig, req: HttpRequest, error: config.onMaintenance?.(); } else if ([502, 503, 504].includes(status)) { config.onServerBusy?.(status, retryAfterSeconds); - } else if ([400, 422, 500].includes(status) && error.error?.message) { + } else if ([400, 409, 422, 500].includes(status) && error.error?.message) { config.onServerError?.(error.error.message); } // Every other status (404, 418, …) is left to the caller — no generic alert. @@ -494,7 +503,7 @@ const dispatchError = (config: KitHttpConfig, req: HttpRequest, error: * For every other error, `offlineFallback` is consulted first; otherwise the error is classified by * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→ * `onNetworkError` (when connected), `429`→`onRateLimited`, maintenance `503`→`onMaintenance`, - * other `502`/`503`/`504`→`onServerBusy`, and `400`/`422`/`500` with a body message→`onServerError`. + * other `502`/`503`/`504`→`onServerBusy`, and `400`/`409`/`422`/`500` with a body message→`onServerError`. * * @param request - The outgoing request. * @param next - The next handler in the interceptor chain.