Skip to content

Commit 16d3201

Browse files
Merge pull request #2522 from thiagomini/patch-5
docs(exception-filters): docs for error options
2 parents 61bef8b + 0ea5584 commit 16d3201

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

content/exception-filters.md

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,16 +60,24 @@ in the `response` argument. To override the entire JSON response body, pass an o
6060
The second constructor argument - `status` - should be a valid HTTP status code.
6161
Best practice is to use the `HttpStatus` enum imported from `@nestjs/common`.
6262

63-
Here's an example overriding the entire response body:
63+
There is a **third** constructor argument (optional) - `options` - that can be used to provide an error [cause](https://nodejs.org/en/blog/release/v16.9.0/#error-cause). This `cause` object is not serialized into the response object, but it can be useful for logging purposes, providing valuable information about the inner error that caused the `HttpException` to be thrown.
64+
65+
Here's an example overriding the entire response body and providing an error cause:
6466

6567
```typescript
6668
@@filename(cats.controller)
6769
@Get()
6870
async findAll() {
69-
throw new HttpException({
71+
try {
72+
await this.service.findAll()
73+
} catch (error) {
74+
throw new HttpException({
7075
status: HttpStatus.FORBIDDEN,
7176
error: 'This is a custom message',
72-
}, HttpStatus.FORBIDDEN);
77+
}, HttpStatus.FORBIDDEN, {
78+
cause: error
79+
});
80+
}
7381
}
7482
```
7583

@@ -130,6 +138,22 @@ Nest provides a set of standard exceptions that inherit from the base `HttpExcep
130138
- `GatewayTimeoutException`
131139
- `PreconditionFailedException`
132140

141+
All the built-in exceptions can also provide both an error `cause` and an error description using the `options` parameter:
142+
143+
```typescript
144+
throw new BadRequestException('Something bad happened', { cause: new Error(), description: 'Some error description' })
145+
```
146+
147+
Using the above, this is how the response would look:
148+
149+
```json
150+
{
151+
"message": "Something bad happened",
152+
"error": "Some error description",
153+
"statusCode": 400,
154+
}
155+
```
156+
133157
#### Exception filters
134158

135159
While the base (built-in) exception filter can automatically handle many cases for you, you may want **full control** over the exceptions layer. For example, you may want to add logging or use a different JSON schema based on some dynamic factors. **Exception filters** are designed for exactly this purpose. They let you control the exact flow of control and the content of the response sent back to the client.

0 commit comments

Comments
 (0)