Naalya Handbook

Error handling and logging

Services throw HttpExceptions, one global filter turns them into the error envelope, and pino writes one masked line per request.

On this API you don't return errors, you throw them. A service that can't find a campus throws NotFoundException; the global AllExceptionsFilter turns every throw into the same JSON envelope; pino-http writes one log line per request with the error on it.

Throw, don't return

apps/server/src/app/campus/campus.service.ts
async findOne(id: string) {
  const campus = await this.campusRepository.findOne({ where: { id } });
  if (!campus) throw new NotFoundException('Campus not found');
  this.permissionScope.assertCanAccess(Action.READ, Resource.CAMPUS, campus);
  return campus;
}

The exception class sets the status code. Pick the class that fits the situation.

SituationThrowStatus
The record doesn't existNotFoundException404
A duplicate, or the wrong state (email taken, already archived)ConflictException409
Bad input or a broken ruleBadRequestException400
Signed in but not allowedForbiddenException403
Missing, expired or bad tokenUnauthorizedException401
A throttled route, or the daily wrong-code cap on stagingThe throttler, or HttpException429

The controller just returns the service call. Never build an error response yourself with @Res().

The envelope

Every error the filter sends matches ErrorResponseDto.

FieldContents
statusCode, error404, "Not Found"
messageThe sentence you threw, or Validation failed.
detailsPer-field validation messages (400)
missingFieldsFields still needed, e.g. an incomplete application
attachmentsWhat blocks a delete, e.g. [{ resource: 'enrollment', count: 214 }] (409)
path, timestampWhere and when
requestIdThe X-Request-Id, the same id as on the log line

To send missingFields or attachments, throw with an object body: new BadRequestException({ message: 'Application is incomplete', missingFields }).

The filter turns each kind of error into a response.

Error thrownResponse sent
An HttpExceptionIts own status, error and message
A body-parser error with a 4xx status (body too large, bad charset)That status and message
A Postgres 22P02 whose rejected value is one segment of the path404 with Not found.
Anything else500 with Unexpected error., so no stack or detail reaches the client

A bad id in the path is that 22P02 row. all-exceptions.filter.ts at API main d0fbb403 reads the driver message invalid input syntax for type uuid, and answers Not found. only when that rejected text is a segment of the path, before the query string. Any other database failure stays a 500. The filter test was not run.

A full throttle bucket is 429. The limits, and the staging 403 This account is suspended when a token is minted, are on Authentication across the platforms and Auth & Permissions. Those routes were read at API staging 6308a8a1. They were not called.

A 5xx is also logged as Unhandled exception with the error and recorded on the OpenTelemetry span, so it shows in Dash0. A 4xx is an expected outcome and is not.

Documenting failures

DecoratorWhere it goes
@ApiAuthErrorResponses()Once on the controller: 401 and 403
@ApiNotFoundErrorResponse('Campus not found.'), @ApiConflictErrorResponse(...), @ApiBadRequestErrorResponse(...)On each handler that can actually throw them

injectGlobalErrorResponses adds 401, 403 and 500 to every operation when the spec is built (401 and 403 skipped on @Public() routes) and never overwrites one you declared. So document only the specific 4xx a route can throw, with the real message.

Logging

In code, log through AppLogger (a typed wrapper over nestjs-pino), always as an object:

this.logger.warn({ msg: 'Retrying the provider', meta: { requestId }, data: { attempt }, err });

Nest's string-first Logger API is not supported.

Each request gets one line from pino-http when it finishes (LOGGING_REQUEST_LOGGER_ENABLED, on by default). The line's contents depend on whether the request failed.

Logged itemSuccessful requestFailed request
Method, path, full URL, status, timeYesYes
Request bodyYesYes
Request headersA few (user agent, referer, origin, content type and length, request id)All
The error message and detailsNoYes
Response body and headersNoNo
replica (which API copy) and requestIdYesYes

Cookies are always dropped. Levels: warn for 4xx, error for 5xx, info otherwise. A 401 on /auth/me is info, because the Hub gets one every time its token expires.

Only passwords and sign-in tokens are masked

maskSignIn replaces password fields, otp, token, accessToken, refreshToken, idToken, the Authorization header, x-api-key and ?token= in URLs with ***, on every line. Everything else in a request body is logged as sent, including names and contact details. Don't add other masking or size caps (that's the API's own rule), and never log a secret yourself, in a message, an error, or a trace attribute.

On API staging 6308a8a1 (not on main d0fbb403) the same mask also covers a key whose name ends in secret. logger.config.ts was read there. The logger test was not run. A merge to staging is not a running deploy.

Quiet routes and tracing

Six routes are called so often that their successful calls are not logged or traced: GET /realtime/token, POST /realtime/subscription-token, POST /realtime/observer-tokens, POST /realtime/online, GET /health and GET /notifications/unread-count (all under /api/v1). Failures still log. The list is QUIET_ROUTES in libs/shared/src/logging/quiet-routes.ts; add a method and path there to quieten another.

SettingEffect
OTEL_EXPORTER_OTLP_ENDPOINT unsetLogs go to stdout only; no traces leave the app
SetEvery line and trace goes to Dash0; Railway's stdout keeps only warnings and errors
OTEL_DETAILED_TRACING=1Adds Nest, Postgres and Redis spans to the server's traces. The worker, audit and clinic apps always trace in full

Mistakes to avoid

  • The wrong class is the wrong status: a missing record as 400, or a duplicate as 404.
  • Swallowing: a catch that returns null sends the client a 200 for a failure and records nothing.
  • Re-throwing as a plain Error turns a clean 404 into a 500. Re-throw an HttpException.
  • @Res() responses skip the envelope.

Where to go next

On this page