Course outline

NestJS / Basic: modules and request contracts / Lesson 7

Exception filters and safe HTTP errors

Map a specific application exception to a safe response while recognizing adapter and transaction boundaries.

About 3 min readContent reviewed
On this page

Lesson goals

  • Explain the role of a Nest exception filter.
  • Map a defined exception without leaking internal details.
  • Test the response and durable state separately.

Classify the failure

A request may fail in a guard, pipe, controller, provider or external dependency. A filter can shape selected exception responses, but it does not replace authorization or undo partial writes. Define stable public status and fields for expected failures, and avoid returning stack traces, database messages or credentials. Preserve safe server-side diagnostics for unexpected failures without copying sensitive request bodies.

Define a specific exception

The first fragment defines an application-specific missing-record exception. Throw it only when the application’s policy permits the caller to learn that the record is absent. A database outage and a missing record are different outcomes and should not be collapsed into one exception. A specific type lets the filter handle the intended case while leaving other errors to their configured handlers.

typescript Define a specific application exception
export class RecordMissing extends Error {}

The application decides when this error is appropriate and what information may be disclosed.

Map the exception

The filter fragment catches the defined type and returns a safe 404 response using the Express adapter’s response API. It assumes the filter is registered in the intended application context. Other platform adapters have different response APIs, so verify the chosen adapter rather than copying this fragment blindly. Keep the public response stable and include a safe correlation identifier only if the application has established one.

typescript Map it using an Express-adapter filter
@Catch(RecordMissing)
export class MissingFilter implements ExceptionFilter {
  catch(_error: RecordMissing, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse<Response>();
    response.status(404).json({ error: 'Record not found' });
  }
}

The filter must be registered and uses the Express response API. Other adapters require their own compatible response handling.

Protect state independently

A filter runs after an exception and changes the response, not the transaction’s semantics. Define commit and rollback in the persistence layer, and test a failure between related writes using a disposable database. If an external effect happened before failure, a database rollback cannot reverse it. Use an explicit idempotency or recovery design for that separate boundary.

Verify the complete path

Use a test application with the actual filter registration to request a missing synthetic record and assert status and safe response fields. Add an allowed control and a separate unexpected-failure case. For a denied or failed write, inspect stored state as well as the HTTP response. A unit test that calls the filter directly cannot prove guard order, adapter behavior or repository rollback.

Common errors and fixes

Every failure is returned as not found

Why it happens
A broad filter hides infrastructure and programming errors.
How to fix it
Catch only the intended exception and handle other failures separately.
Prevent it next time
Test missing-record and dependency-failure cases.

An error body reveals database details

Why it happens
An internal exception message was returned to the client.
How to fix it
Return a stable safe message and keep controlled diagnostics server-side.
Prevent it next time
Test response fields with synthetic sensitive values.

A failure response leaves partial writes

Why it happens
The filter was assumed to roll back persistence.
How to fix it
Define a transaction around the intended database changes.
Prevent it next time
Force failure between writes and inspect committed state.

2 practice exercises

1. Should an unavailable database become a missing-record response?

Show worked solution

Not automatically. Distinguish infrastructure failure from an authorized lookup that found no record. Apply the application’s error contract and avoid exposing connection details.

2. How can you verify rollback after a failed update?

Show worked solution

Use a disposable database, trigger failure between related writes and inspect state from a fresh transaction. Assert the filter’s response separately; the filter itself does not perform rollback.

Key takeaways

  • Catch specific expected exceptions and return safe responses.
  • Filter behavior, authorization and transaction recovery are separate boundaries.

Official references