You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/exception-filters.md
+27-3Lines changed: 27 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -60,16 +60,24 @@ in the `response` argument. To override the entire JSON response body, pass an o
60
60
The second constructor argument - `status` - should be a valid HTTP status code.
61
61
Best practice is to use the `HttpStatus` enum imported from `@nestjs/common`.
62
62
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:
64
66
65
67
```typescript
66
68
@@filename(cats.controller)
67
69
@Get()
68
70
asyncfindAll() {
69
-
thrownewHttpException({
71
+
try {
72
+
awaitthis.service.findAll()
73
+
} catch (error) {
74
+
thrownewHttpException({
70
75
status: HttpStatus.FORBIDDEN,
71
76
error: 'This is a custom message',
72
-
}, HttpStatus.FORBIDDEN);
77
+
}, HttpStatus.FORBIDDEN, {
78
+
cause: error
79
+
});
80
+
}
73
81
}
74
82
```
75
83
@@ -130,6 +138,22 @@ Nest provides a set of standard exceptions that inherit from the base `HttpExcep
130
138
-`GatewayTimeoutException`
131
139
-`PreconditionFailedException`
132
140
141
+
All the built-in exceptions can also provide both an error `cause` and an error description using the `options` parameter:
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
+
133
157
#### Exception filters
134
158
135
159
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