Skip to content

Commit 1a16294

Browse files
authored
docs(exception-filters): docs for error options
add docs explaining how to use the new `options` object containing both the `cause` and `description`.
1 parent 61bef8b commit 1a16294

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

content/exception-filters.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,16 +60,25 @@ 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+
66+
Here's an example overriding the entire response body and providing an error cause:
6467

6568
```typescript
6669
@@filename(cats.controller)
6770
@Get()
6871
async findAll() {
69-
throw new HttpException({
72+
try {
73+
await this.service.findAll()
74+
} catch (error) {
75+
throw new HttpException({
7076
status: HttpStatus.FORBIDDEN,
7177
error: 'This is a custom message',
72-
}, HttpStatus.FORBIDDEN);
78+
}, HttpStatus.FORBIDDEN, {
79+
cause: error
80+
});
81+
}
7382
}
7483
```
7584

@@ -130,6 +139,22 @@ Nest provides a set of standard exceptions that inherit from the base `HttpExcep
130139
- `GatewayTimeoutException`
131140
- `PreconditionFailedException`
132141

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

135160
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)