What does NestJS do with errors by default, and why isn't it enough?
NestJS ships with a built-in global exception layer. Any exception that a route handler, guard, pipe, or interceptor doesn't handle ends up there, and it turns the exception into an HTTP response. For HttpException and its subclasses (NotFoundException, BadRequestException, and the rest), the response uses the exception's status code and a JSON body built from statusCode, message, and usually error, which holds the reason phrase, such as "Bad Request". Anything the framework doesn't recognize as an HttpException, whether a TypeError, a database driver error, or a rejected promise from a third-party SDK, becomes a generic 500 with the message "Internal server error". This default is reasonable because it prevents stack traces and internal details from reaching clients.
The problem is that this shape is too loose to serve as a contract:
messagechanges type. It is a string for most exceptions but an array of strings whenValidationPiperejects a payload, so clients have to check its type before reading it.- The body can be anything. If you pass an object to an
HttpExceptionconstructor, that object becomes the response body. Over time, individual controllers drift into their own field names and nesting. - There are no stable identifiers. Clients end up matching on human-readable text, and that breaks the first time someone rewords a message.
- The content type isn't specific. Errors go out as plain
application/json, so nothing in the response tells a client "this is an error document."
A single-frontend app can live with this. Teams that publish public APIs, serve several client teams, or generate SDKs need errors that machines can parse, and that is where a standard format pays off.
import { Controller, Get, HttpException, HttpStatus, NotFoundException, Param } from '@nestjs/common';
@Controller('users')
export class UsersController {
// Built-in subclass: the default layer builds the body for you.
// 404 -> {"message":"User 42 not found","error":"Not Found","statusCode":404}
@Get(':id')
findOne(@Param('id') id: string) {
throw new NotFoundException(`User ${id} not found`);
}
// Object passed to HttpException: sent verbatim, so each controller can invent its own shape.
// 429 -> {"code":"QUOTA_EXCEEDED","details":{"limit":100}}
@Get(':id/exports')
exports() {
throw new HttpException({ code: 'QUOTA_EXCEEDED', details: { limit: 100 } }, HttpStatus.TOO_MANY_REQUESTS);
}
// Not an HttpException: collapses into a generic 500 and the cause is hidden.
// 500 -> {"statusCode":500,"message":"Internal server error"}
@Get(':id/avatar')
avatar() {
throw new Error('connect ECONNREFUSED 10.0.0.5:5432');
}
}
// ValidationPipe rejection on a POST body: the same field is now an array.
// 400 -> {"message":["email must be an email"],"error":"Bad Request","statusCode":400}
//
// All four responses are sent as Content-Type: application/json.
// None of them carries a stable, machine-readable error identifier.
Four error paths through NestJS's default exception layer produce four incompatible bodies: message is sometimes a string and sometimes an array, the shape can be arbitrary, unknown errors become an opaque 500, and every response is sent as plain application/json.
What is RFC 9457 Problem Details?
RFC 9457 defines a standard JSON error document served with the application/problem+json media type. A client that sees that content type knows the body's shape before parsing it, whatever endpoint produced it.
The format has five standard members, all optional:
type: a URI reference that identifies the problem category. It is the primary key clients branch on. If omitted, it defaults toabout:blank.title: a short, human-readable summary of the type. It should not change from one occurrence to the next.status: the HTTP status code, copied into the body for convenience. It is advisory; the response status line is authoritative.detail: an explanation specific to this occurrence. It is for humans, not for parsing.instance: a URI reference that identifies this specific occurrence, which is useful for correlating with logs.
about:blank means "no semantics beyond the status code," so its title should match the standard HTTP reason phrase, such as Not Found. Any other member is an extension member, for example errors or traceId. Clients must ignore extensions they don't recognize, so you can add fields without breaking older consumers.
RFC 9457 obsoletes RFC 7807. Documents that conform to RFC 7807 remain valid under RFC 9457.
Use type URIs under a domain your organization controls, for example a dedicated path such as /problems/ on your API's own domain. Treat them like endpoint paths. Clients will hard-code them, so renaming one is a breaking change. Version them deliberately and never reuse one for a different meaning.
| Concern | NestJS default | Problem Details |
|---|---|---|
| Content type | application/json |
application/problem+json |
| Status | statusCode |
status |
| Category | error (reason phrase) |
type (stable URI) |
| Summary | message (string or array) |
title (fixed per type) |
| Specifics | mixed into message |
detail |
| Occurrence ID | none | instance |
| Custom fields | ad hoc | extension members |
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{
"statusCode": 404,
"message": "Account 4821 does not exist",
"error": "Not Found"
}
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "/problems/account-not-found",
"title": "Account not found",
"status": 404,
"detail": "Account 4821 does not exist",
"instance": "/accounts/4821",
"traceId": "7f3c2a9e1b4d4c0a"
}
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "about:blank",
"title": "Not Found",
"status": 404
}
The default NestJS 404 body next to the equivalent RFC 9457 Problem Details responses, one with an organization-owned type URI and an extension member and one using about:blank, with each standard member mapped to the NestJS field it replaces.
How does it work? How a NestJS exception filter turns errors into Problem Details
In short, one global exception filter sits between your code and the HTTP response. Every thrown error passes through it. The filter converts the error into a Problem Details object, sets the application/problem+json content type, and writes the response. The rest of this section walks through the mechanics.
When a controller, service, guard, interceptor or pipe throws, the error propagates up through the call chain until Nest's exception layer catches it. Nest then looks for a filter whose @Catch() list matches the thrown type. It checks method-scoped filters first, then controller-scoped, then global. The first match writes the response, and the built-in default handler applies only if nothing matched. Because of this ordering, a route can override the global Problem Details shape for a special case without any branching inside the global filter.
@Catch() with no arguments matches everything, including plain Error objects and non-Error values thrown by third-party code. That breadth is what you want for a single Problem Details contract. It also means the filter must handle unknown inputs defensively and must never echo raw messages from unexpected errors.
The filter receives an ArgumentsHost, which abstracts over transport. Call host.getType() first. A global filter also runs for microservice and WebSocket contexts, where there is no HTTP response to write. For those contexts, return or rethrow instead of calling switchToHttp().
To write the response, inject HttpAdapterHost and use the adapter's reply and setHeader methods rather than calling Express's res.status().json() directly. The same filter then works on both Express and Fastify, and you can set Content-Type: application/problem+json portably.
Some errors never reach a filter:
- Errors from middleware mounted directly on the underlying platform, outside Nest's routing.
- Errors raised after headers have been sent, when the status code can no longer change.
- Failures partway through a streamed response.
+------------------------------------------------------------+
| Controller, Service, Guard, Interceptor, Pipe: throw err |
+-----------------------------+------------------------------+
v
+------------------------------------------------------------+
| Nest exception layer: find filter whose @Catch() matches |
| [1] method-scoped -> [2] controller -> [3] global |
| first match writes response; none -> built-in default |
+-----------------------------+------------------------------+
v
+------------------------------------------------------------+
| @Catch() catch-all: catch(exception, host: ArgumentsHost) |
| switch on host.getType() |
+---------+------------------------------+-------------------+
| 'http' | 'rpc' / 'ws'
v v
+--------------------------------+ +----------------------+
| HttpAdapterHost.httpAdapter | | return or rethrow; |
| .setHeader('Content-Type', | | no HTTP response, |
| 'application/problem+json') | | skip switchToHttp() |
| .reply(res, body, status) | +----------------------+
+---------------+----------------+
v
Express or Fastify response (problem+json)
+- Bypasses the exception layer (no filter runs) ------------+
| x middleware mounted on the platform, outside Nest routing |
| x errors after headers are sent (status can't change) |
| x failures partway through a streamed response |
+------------------------------------------------------------+
A thrown error flows to Nest's exception layer, where the first matching filter (method, then controller, then global) checks host.getType() and writes an application/problem+json response through HttpAdapterHost; errors outside that path never reach a filter.
How do you implement a global Problem Details exception filter?
Step 1: Define a domain error base class. Give it readonly type (a URI), title, and status fields, and have each concrete error such as OrderNotFoundError subclass it. Services throw these errors without importing anything from @nestjs/common, so the domain layer stays transport-agnostic and can be reused from a queue consumer or CLI.
Step 2: Write a pure mapping function. It takes unknown and returns a Problem Details object. Handle three cases:
HttpException: usegetStatus()andgetResponse().- Domain errors: copy
type,title, andstatusfrom the error. - Anything else: always 500 with a generic
detail.
Because the function has no framework dependencies, you can unit-test it exhaustively.
Step 3: Implement the filter. Implement ExceptionFilter and inject HttpAdapterHost rather than typing the response as Express or Fastify. Call httpAdapter.setHeader(response, 'Content-Type', 'application/problem+json') and then httpAdapter.reply(response, body, status).
Check host.getType() first. If the context isn't 'http', rethrow or delegate, because an RPC or WebSocket context has no response object to write to.
Step 4: Correlate and log. Read an incoming request ID header or generate one. Log the full error, including the stack and cause, on the server. Return the ID as an extension member such as requestId. For 5xx responses, never put stack traces or ORM messages in detail. They leak schema and infrastructure details.
Alternative to a growing switch: Have each error class implement a toProblem() method. The mapper then checks for that method and calls it, so adding a new error type doesn't require editing the filter.
import { ArgumentsHost, Catch, ExceptionFilter, Logger } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { randomUUID } from 'node:crypto';
import { toProblem } from './problem-mapper'; // pure mapper from Step 2
@Catch() // no arguments: catch everything, including unknown errors
export class ProblemDetailsFilter implements ExceptionFilter {
private readonly logger = new Logger(ProblemDetailsFilter.name);
constructor(private readonly adapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
// RPC and WebSocket contexts have no HTTP response to write to.
if (host.getType() !== 'http') throw exception;
const { httpAdapter } = this.adapterHost; // works for Express and Fastify
const ctx = host.switchToHttp();
const request = ctx.getRequest();
const response = ctx.getResponse();
// Reuse the caller's correlation ID if it sent one, otherwise generate one.
const incoming = request.headers?.['x-request-id'];
const requestId = typeof incoming === 'string' ? incoming : randomUUID();
// Status, type, title and a safe detail. Unknown errors map to a generic 500.
const problem = toProblem(exception);
// Log the full error, stack included, on the server only.
const stack = exception instanceof Error ? exception.stack : String(exception);
this.logger.error(`[${requestId}] ${problem.status} ${problem.title}`, stack);
const body = {
...problem,
instance: httpAdapter.getRequestUrl(request),
requestId, // extension member the client can quote to support
};
httpAdapter.setHeader(response, 'Content-Type', 'application/problem+json');
httpAdapter.reply(response, body, problem.status);
}
}
// main.ts: app.useGlobalFilters(new ProblemDetailsFilter(app.get(HttpAdapterHost)));
A global catch-all NestJS filter that skips non-HTTP contexts, delegates mapping to a pure function, logs the full error with a correlation ID, and replies with an application/problem+json body through the platform-agnostic HttpAdapterHost.
Should you register the filter with useGlobalFilters or APP_FILTER?
app.useGlobalFilters(new ProblemDetailsFilter()) in main.ts is the shortest path, but you construct the instance yourself, outside the DI container. The filter cannot inject a logger, ConfigService, or the error mapper from the previous section. You can work around this by passing app.get(...) results into the constructor, but that wiring is manual. A second cost is easier to miss: main.ts doesn't run in e2e tests built with Test.createTestingModule. Unless every test repeats the call, your tests will see Nest's default error shape instead of Problem Details.
Registering { provide: APP_FILTER, useClass: ProblemDetailsFilter } in a module's providers makes the filter a regular provider. Nest resolves its dependencies, and any test module that imports that module picks it up automatically. The filter still applies globally, whichever module declares it.
| Concern | useGlobalFilters |
APP_FILTER |
|---|---|---|
| Dependency injection | No, you wire it manually | Yes |
| Active in e2e test modules | Only if repeated per test | Yes, via module import |
| Where it lives | Bootstrap code | Module metadata |
How scoped filters interact
Nest checks filters from most specific to least: method-scoped (@UseFilters on a handler), then controller-scoped, then global. The first filter whose @Catch() types match the exception handles it, and no other filter runs. A method filter that catches only HttpException lets a TypeError fall through to the global filter.
Choose one global registration style per application, preferably APP_FILTER. If you register global filters both ways, a reader has to check two places to work out which filter produced a response.
How do you map ValidationPipe errors and test the filter?
By default, ValidationPipe throws a BadRequestException whose message is an array of English sentences such as "email must be an email". Clients end up parsing those strings, and the strings change whenever someone edits a decorator option. Override exceptionFactory instead. It receives the ValidationError[] produced by class-validator, and from it you throw your own domain error, for example RequestValidationError, which carries structured field failures. Walk nested children so that a failure on address.postcode keeps its full path.
The mapper turns that error into a 400 or 422 Problem Details object. Put the failures in an errors extension member, which is an array of objects with a field path, a constraint key such as isEmail, and a human-readable detail. Document this shape as part of your API contract. Clients branch on the constraint key, and the wording of detail can change without breaking them.
Write the mapper as a pure function that takes an exception and returns a status and a body. You can then unit-test it once per error class (domain errors, HttpException subclasses, validation errors, unknown throws) with no Nest context and no HTTP layer. The e2e tests should boot the real module and send a request with an invalid body. Assert three things: the status code, a Content-Type of application/problem+json, and the body shape, including errors. The e2e tests also show why APP_FILTER is the better registration. A filter registered with useGlobalFilters in main.ts is missing from a test app built from the testing module, so your tests would exercise different error handling than production does.
This setup saves engineering time. With per-controller try/catch blocks, every endpoint needs its own error assertions, and the error formats drift apart between endpoints. With one mapper and one shared test suite, adding an endpoint requires no new error-handling tests.
How does it affect development cost?
The cost profile shifts from a recurring per-endpoint cost to a mostly one-time cost.
Upfront costs:
- Designing the domain error base class and the set of
typeURIs, including naming and versioning rules. - Writing the pure mapper, the filter, and the
ValidationPipeexceptionFactory. - Writing the mapper's unit tests and a small set of e2e tests for the error contract.
- Documenting each
type, itstitle, and any extension members such aserrorsorrequestId. - If existing clients parse the default
statusCode/message/errorshape, planning a migration path, such as content negotiation onAcceptor a deprecation window.
Ongoing costs:
- Adding a new error means adding a domain error class (and, with the
toProblem()approach, nothing else). Without self-describing errors, it also means one new branch in the mapper and one new unit test. - Reviewing
detailtext for data leaks, because it reaches clients. - Treating
typeURIs and extension members as a public contract, which means changes go through the same review as endpoint changes.
Costs that go down:
- Controllers and services no longer contain error-formatting code, so there is less code to write and review per endpoint.
- Client teams and SDK generators implement error handling once against one documented shape, instead of special-casing endpoints.
- Fewer bugs where an endpoint returns an ad hoc body that a client can't parse.
The main risk to cost is a poorly designed mapper. A fallback branch that maps unknown errors to 4xx hides server bugs, and fixing that after clients depend on the behavior is more expensive than getting it right initially.
As an illustrative estimate with assumed inputs: suppose an API has an assumed 40 endpoints and each one has an assumed 3 distinct error paths it formats itself. That is 120 places where the error body is constructed and, ideally, asserted in tests. With a single mapper, the number of places that build an error body drops to one, and the number of mapper tests scales with the number of error classes rather than the number of endpoints. The actual figures depend entirely on your codebase; the point is the change in what the cost scales with.
How can it save engineering time?
The time savings come from removing repeated work and shortening investigations:
- No per-endpoint error formatting. Handlers throw domain errors and move on. Nobody writes try/catch blocks just to reshape an error into JSON.
- Fewer tests per endpoint. The mapper is tested once per error class, and a few e2e tests confirm the contract. New endpoints inherit correct error handling without new error-format tests.
- Faster client integration. Frontend, mobile, and SDK teams branch on
typeand readerrorsthe same way everywhere. They don't need to ask backend engineers what a specific endpoint returns on failure. - Faster debugging. The
requestIdextension member andinstancelet support staff and engineers go straight from a client-reported error to the matching server log entry, which contains the full stack trace. - Less churn from wording changes. Because clients key on
typeand constraint keys rather thandetailtext, editing messages doesn't trigger client fixes. - Shorter code reviews. Reviewers check that a handler throws the right domain error instead of checking a hand-built error body for consistency with other endpoints.
- Cheaper onboarding. New engineers learn one error pattern, not a different convention per controller.
These savings depend on the team actually using the pattern. If some controllers still build ad hoc HttpException bodies, clients go back to special-casing, and much of the benefit disappears. A lint rule or code review checklist item against passing raw objects to HttpException helps keep the contract intact.
When should you avoid a catch-all filter, and what are the alternatives?
A catch-all filter has costs. The worst is generous mapping: if the fallback branch turns an unknown TypeError into a clean 400, a server bug looks like a client mistake and never reaches your alerts. Unrecognized errors should stay 500 with a generic detail. Once published, type URIs and extension members are contract. Renaming out-of-stock or dropping a balance member breaks every client that branches on them. Existing clients that parse the default statusCode/message/error shape will break on cutover. To avoid that, return application/problem+json only when the Accept header requests it, or serve both shapes through a deprecation window. detail can leak data: "user 4821 not found" confirms that the ID exists. An HTTP-centric filter also misbehaves under GraphQL, WebSockets and microservices, which have their own error conventions. Check host.getType() and delegate for those transports. Finally, a global mapper ends up coupled to the exception types of every module.
| Approach | Fits when | Main cost |
|---|---|---|
| NestJS default shape | Internal APIs, few consumers | No machine-readable type |
| Per-controller filters | One bounded context needs Problem Details | Formats drift between controllers |
| Transport-specific handling | Mixed HTTP, GraphQL and microservices | Several mappers to maintain |
| Registry or self-describing errors | Many teams own exceptions | Upfront design work |
The work is front-loaded: you design URIs, review detail text and add transport guards. The payoff comes later. Client integrations branch on stable type values, support can trace a request through instance, and the error documentation comes from a single source.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs exception filter, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.