In NestJS 12, what does the errorCode option on HttpException and its built-in subclasses put in the response, and how does it differ from cause?
answer
- the third argument, the options object
- something a client can branch on
- serialized versus kept for logs
- an object body is sent unchanged
basics
~10 sIn NestJS 12, errorCode is a stable string Nest adds to a string-message body as an errorCode field for clients to branch on; cause holds the original error for logging and is never serialized.
solid answer
~40 sNestJS 12 added `errorCode` to `HttpExceptionOptions`, beside `cause` and `description`. `throw new BadRequestException('Password is too weak', { errorCode: 'WEAK_PASSWORD' })` sends `{"message":"Password is too weak","error":"Bad Request","statusCode":400,"errorCode":"WEAK_PASSWORD"}`, so a client can tell a weak password from an invalid email without parsing the message. `HttpException` accepts it too: `new HttpException('Forbidden', HttpStatus.FORBIDDEN, { errorCode: 'ACCOUNT_SUSPENDED' })`. `cause` is the opposite: it keeps the underlying error on the exception for logs and is never serialized. One catch: when the first argument is an object, Nest sends that object as the body and adds no `errorCode`, and a custom filter that builds its own body must copy `exception.errorCode` itself.
code
typescript · 15 linesimport { BadRequestException, Body, Controller, Post } from '@nestjs/common';
@Controller('accounts')
export class AccountsController {
@Post()
create(@Body() body: { password: string }) {
if (body.password.length < 12) {
// 400 {"message":"Password is too weak","error":"Bad Request","statusCode":400,"errorCode":"WEAK_PASSWORD"}
throw new BadRequestException('Password is too weak', {
errorCode: 'WEAK_PASSWORD',
});
}
return { created: true };
}
}go deeper
Recall that errorCode normally lands in the response body as an errorCode field while cause never does; both go in the exception's options object.
Explain the three options, where each lands in the body, and why an object first argument or a custom filter body drops errorCode.
Show you would treat the code vocabulary as API contract, keep custom filters copying exception.errorCode, and keep internals in cause.
Decide whether the team adopts a shared error-code catalogue on top of statuses, who owns it, and how codes are versioned once clients depend on them.
## The problem errorCode solves An HTTP status is coarse. A sign-up endpoint can fail with **400 Bad Request** because the email is malformed, because the password is too weak, or because a field is missing. A client that wants to highlight the right form field then has to parse the human-readable `message`, which breaks the day someone rewords it or translates it. NestJS 12 adds a **machine-readable error code** to its HTTP exceptions for this. The migration guide from 11 to 12 records it: `HttpExceptionOptions` accepts a new `errorCode` property, and it is serialized into the response body. ## The options object Every built-in HTTP exception takes an options object as its last argument, and in NestJS 12 `HttpExceptionOptions` has three optional fields: | Option | Type | Goes into the body? | Purpose | |---|---|---|---| | `errorCode` | string | yes, as `errorCode`, unless you pass an object body | a stable identifier clients branch on | | `description` | string | as `error` on a built-in subclass given a message string | the short status phrase, such as `'Bad Request'`, by default | | `cause` | unknown | no | the original error, for logs and for a custom filter | On a built-in subclass the options are the second argument, which may instead be a plain description string; on `HttpException` itself they are the third, after the status. ## What the built-in filter sends With a string message on a built-in subclass: ```typescript throw new BadRequestException('Password is too weak', { errorCode: 'WEAK_PASSWORD', }); ``` the body is `{"message":"Password is too weak","error":"Bad Request","statusCode":400,"errorCode":"WEAK_PASSWORD"}`. On `HttpException` with a string response, `new HttpException('Forbidden', HttpStatus.FORBIDDEN, { errorCode: 'ACCOUNT_SUSPENDED' })` gives `{"statusCode":403,"message":"Forbidden","errorCode":"ACCOUNT_SUSPENDED"}`. The code is also stored on the exception as the `errorCode` property, so your own code and filters can read it. ## Where errorCode does not appear Two cases send no `errorCode` field even though you set it: 1. **An object as the first argument.** `new HttpException({ code: 'X' }, 409, { errorCode: 'E1' })` responds with exactly `{"code":"X"}`. When you pass an object, Nest treats it as the complete body and serializes it unchanged; the code is still on `exception.errorCode`, but if clients need it in the body you put it in the object yourself. 2. **A custom filter that builds its own body.** A filter decorated `@Catch(HttpException)` that sends `{ statusCode, timestamp, path }` drops the code unless it reads `exception.errorCode` and adds it. A filter that extends `BaseExceptionFilter` and calls `super.catch()` keeps it, because the base filter writes the same bodies as the default. ## errorCode versus cause The two options are easy to mix up because both sit in the same object, but they point in opposite directions: - **`errorCode` is for the client.** It is part of the public contract of your API; once clients branch on `WEAK_PASSWORD`, renaming it is a breaking change. - **`cause` is for you.** It chains the original error, such as a driver exception caught in a service and rethrown as a `ServiceUnavailableException`, so a logger or a monitoring filter can see what really happened. The docs state that it is never serialized into the response. Putting an internal detail into `errorCode`, such as a database constraint name, therefore publishes it; putting a client-facing code into `cause` hides it. ## Reading the code on the client A client that receives an error body should branch in a fixed order: 1. Check `errorCode` first when it is present; it is the most specific signal. 2. Fall back to the HTTP status when there is no code, which is the case for most errors. 3. Show `message` to people, never use it in conditions. Tests can assert on `errorCode` the same way, which makes them robust to rewording the human message. Codes also travel well through an API description, where each code can be listed once with its meaning. ## Good practice - Choose a short, upper-case, documented vocabulary and keep it stable across releases. - Set `errorCode` where several failures share a status; a lone 404 rarely needs one. - When a custom filter reshapes bodies, copy `exception.errorCode` so the contract survives. - Keep the human `message` for people; never make clients parse it again.
- A NestJS 12 custom filter decorated @Catch(HttpException) sends its own body. How does it keep the error code?Read `exception.errorCode`, which the exception stores whenever the option was set, and add it to the body the filter sends, for example only when it is defined. Without that, the filter's own body replaces Nest's default and the code is lost even though the exception carried it.
- Why should an errorCode value never carry internal details such as a database constraint name?Because Nest serializes `errorCode` into the response body; it is part of the public API contract that clients read and branch on. Internal detail belongs in `cause`, which stays on the exception for logging and is never sent to the client.
- Thinks cause is serialized so clients can see the original error.
- Expects errorCode to be merged into an object passed as the body.
- Believes errorCode replaces the HTTP status code in the response.
- Claims Nest 11 already sent an errorCode field in exception bodies.
Assumes NestJS 12; the errorCode option of HttpExceptionOptions was added in 12, so on Nest 11 there is no such option and no errorCode field in the body.