Skip to content

Commit 0136131

Browse files
author
ufec
committed
Update exception-filters.md
There are differences in fastify response api
1 parent 70f5d2e commit 0136131

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

content/exception-filters.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,56 @@ export class HttpExceptionFilter {
182182

183183
> info **Hint** All exception filters should implement the generic `ExceptionFilter<T>` interface. This requires you to provide the `catch(exception: T, host: ArgumentsHost)` method with its indicated signature. `T` indicates the type of the exception.
184184
185+
you can use `response.send()` instead of `response.json()` when using `platform-fastify`, and use `import { FastifyReply as Response, FastifyRequest as Request } from 'fastify';` instead of `import { Request, Response } from 'express';`
186+
187+
like this:
188+
189+
```typescript
190+
@@filename(http-exception.filter)
191+
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
192+
import { FastifyReply as Response, FastifyRequest as Request } from 'fastify';
193+
194+
@Catch(HttpException)
195+
export class HttpExceptionFilter implements ExceptionFilter {
196+
catch(exception: HttpException, host: ArgumentsHost) {
197+
const ctx = host.switchToHttp();
198+
const response = ctx.getResponse<Response>();
199+
const request = ctx.getRequest<Request>();
200+
const status = exception.getStatus();
201+
202+
response
203+
.status(status)
204+
.send({
205+
statusCode: status,
206+
timestamp: new Date().toISOString(),
207+
path: request.url,
208+
});
209+
}
210+
}
211+
@@switch
212+
import { Catch, HttpException } from '@nestjs/common';
213+
214+
@Catch(HttpException)
215+
export class HttpExceptionFilter {
216+
catch(exception, host) {
217+
const ctx = host.switchToHttp();
218+
const response = ctx.getResponse();
219+
const request = ctx.getRequest();
220+
const status = exception.getStatus();
221+
222+
response
223+
.status(status)
224+
.send({
225+
statusCode: status,
226+
timestamp: new Date().toISOString(),
227+
path: request.url,
228+
});
229+
}
230+
}
231+
```
232+
233+
> info **Hint** you must install `fastify`
234+
185235
The `@Catch(HttpException)` decorator binds the required metadata to the exception filter, telling Nest that this particular filter is looking for exceptions of type `HttpException` and nothing else. The `@Catch()` decorator may take a single parameter, or a comma-separated list. This lets you set up the filter for several types of exceptions at once.
186236

187237
#### Arguments host

0 commit comments

Comments
 (0)