Skip to content

Commit ac822f7

Browse files
Merge pull request #2107 from micalevisk/improve-exception-filter-example
doc: replace 'catch everything' example with a platform-agnostic one
2 parents d65a110 + 72f2478 commit ac822f7

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

content/exception-filters.md

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,8 @@ You can add as many filters with this technique as needed; simply add each to th
284284

285285
In order to catch **every** unhandled exception (regardless of the exception type), leave the `@Catch()` decorator's parameter list empty, e.g., `@Catch()`.
286286

287+
In the example below we have a code that is platform-agnostic because it uses the [HTTP adapter](./faq/http-adapter) to deliver the response, and doesn't use any of the platform-specific objects (`Request` and `Response`) directly:
288+
287289
```typescript
288290
import {
289291
ExceptionFilter,
@@ -292,30 +294,35 @@ import {
292294
HttpException,
293295
HttpStatus,
294296
} from '@nestjs/common';
297+
import { HttpAdapterHost } from '@nestjs/core';
295298

296299
@Catch()
297300
export class AllExceptionsFilter implements ExceptionFilter {
298-
catch(exception: unknown, host: ArgumentsHost) {
301+
constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
302+
303+
catch(exception: unknown, host: ArgumentsHost): void {
304+
// In certain situations `httpAdapter` might not be available in the
305+
// constructor method, thus we should resolve it here.
306+
const { httpAdapter } = this.httpAdapterHost;
307+
299308
const ctx = host.switchToHttp();
300-
const response = ctx.getResponse();
301-
const request = ctx.getRequest();
302309

303-
const status =
310+
const httpStatus =
304311
exception instanceof HttpException
305312
? exception.getStatus()
306313
: HttpStatus.INTERNAL_SERVER_ERROR;
307314

308-
response.status(status).json({
309-
statusCode: status,
315+
const responseBody = {
316+
statusCode: httpStatus,
310317
timestamp: new Date().toISOString(),
311-
path: request.url,
312-
});
318+
path: httpAdapter.getRequestUrl(ctx.getRequest()),
319+
};
320+
321+
httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
313322
}
314323
}
315324
```
316325

317-
In the example above the filter will catch each exception thrown, regardless of its type (class).
318-
319326
#### Inheritance
320327

321328
Typically, you'll create fully customized exception filters crafted to fulfill your application requirements. However, there might be use-cases when you would like to simply extend the built-in default **global exception filter**, and override the behavior based on certain factors.

0 commit comments

Comments
 (0)