Skip to content

Commit 20538a1

Browse files
committed
Fix getStatus is not a function
1 parent 0654e89 commit 20538a1

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import { ExceptionFilter, Catch, ArgumentsHost, Logger } from '@nestjs/common';
1+
import {
2+
ExceptionFilter,
3+
Catch,
4+
ArgumentsHost,
5+
HttpException,
6+
} from '@nestjs/common';
27

38
import { Response } from 'express';
49

@@ -7,27 +12,27 @@ import { Response } from 'express';
712
// This class add CORS headers to exception response to avoid misleading CORS error
813
@Catch()
914
export class ApplyCorsToExceptions implements ExceptionFilter {
10-
private readonly logger = new Logger(ApplyCorsToExceptions.name);
1115
catch(exception: any, host: ArgumentsHost) {
12-
try {
13-
const ctx = host.switchToHttp();
14-
const response = ctx.getResponse<Response>();
15-
16-
response.header('Access-Control-Allow-Origin', '*');
17-
response.header(
18-
'Access-Control-Allow-Methods',
19-
'GET,HEAD,PUT,PATCH,POST,DELETE',
20-
);
21-
response.header(
22-
'Access-Control-Allow-Headers',
23-
'Origin, X-Requested-With, Content-Type, Accept',
24-
);
25-
26-
response.status(exception.getStatus()).json(exception.response);
27-
} catch (e) {
28-
this.logger.error(e);
16+
const ctx = host.switchToHttp();
17+
const response = ctx.getResponse<Response>();
2918

19+
if (!response.header) {
3020
return;
3121
}
22+
23+
response.header('Access-Control-Allow-Origin', '*');
24+
response.header(
25+
'Access-Control-Allow-Methods',
26+
'GET,HEAD,PUT,PATCH,POST,DELETE',
27+
);
28+
response.header(
29+
'Access-Control-Allow-Headers',
30+
'Origin, X-Requested-With, Content-Type, Accept',
31+
);
32+
33+
const status =
34+
exception instanceof HttpException ? exception.getStatus() : 500;
35+
36+
response.status(status).json(exception.response);
3237
}
3338
}

0 commit comments

Comments
 (0)