UtilAdded in v16.6Optional

wrHttpErrorText

A sentence for a failed request, in the active language. wrHttpStatus reads the status alone.

Usage

Call it where the request fails and show the result. Outside an injection context, such as a catch, pass an injector. Lives in ngwr/i18n, since the texts are catalog keys.

import { Injector, inject } from '@angular/core';

import { wrHttpErrorText, wrHttpStatus } from 'ngwr/i18n';

export class OrderForm {
  private readonly injector = inject(Injector);

  protected async save(): Promise<void> {
    try {
      await this.api.save(this.order());
    } catch (error) {
      if (wrHttpStatus(error) === 401) return this.session.lost();

      this.toast.danger(
        wrHttpErrorText(error, {
          injector: this.injector,
          overrides: { 409: 'An order with this number already exists.' },
        }),
      );
    }
  }
}

Which text wins

Highest first.

SourceWhen
overrides[status]The screen names the status. A string, or a function of the error.
The response body Only with serverMessage: true: error.error.message, or a body that is a plain string. An empty one, or an HTML page from a proxy, is skipped.
httpError.<status>The catalog has the status: 400, 401, 403, 404, 409, 413, 422, 429 and 503.
httpError.4xx, httpError.5xxAny other status of that class. Both take {{status}}.
httpError.networkStatus 0: offline, CORS, a dropped connection.
httpError.unknownNot an HTTP error, or a status outside 4xx and 5xx.

The texts ship in every ngwr catalog, so register yours with provideWrI18nBaseCatalogs(). With none registered the text is English.

Reword a text

For one screen, use overrides. For the whole app, put the key in your own catalog: it wins over ngwr's.

// app.config.ts
provideWrI18nBaseCatalogs({ en: wrEn, de: wrDe }),
provideWrI18nStaticLoader({
  en: { httpError: { 403: 'Ask your manager for access.' } },
}),

// an API that writes its errors for the reader
wrHttpErrorText(error, { injector, serverMessage: true });

API

NameDescriptionTypeDefault
wrHttpStatus(error)The status of an HttpErrorResponse, or of anything with a numeric status. 0 is a network failure, null is not an HTTP error.(error: unknown) => number | null-
wrHttpErrorText(error, options?)A sentence for the error, in the active language.(error: unknown, options?: WrHttpErrorTextOptions) => string-
options.overridesYour own text per status, 0 being a network failure. A string, or a function of the error.Partial<Record<number, string | ((error: unknown) => string)>>-
options.serverMessagePrefer the sentence in the response body: error.error.message, or a string body.booleanfalse
options.injectorWhere to read WrI18n from. Needed when the call is outside an injection context.Injector-

See also