1
- import { ExceptionFilter , Catch , ArgumentsHost , Logger } from '@nestjs/common' ;
1
+ import {
2
+ ExceptionFilter ,
3
+ Catch ,
4
+ ArgumentsHost ,
5
+ HttpException ,
6
+ } from '@nestjs/common' ;
2
7
3
8
import { Response } from 'express' ;
4
9
@@ -7,27 +12,27 @@ import { Response } from 'express';
7
12
// This class add CORS headers to exception response to avoid misleading CORS error
8
13
@Catch ( )
9
14
export class ApplyCorsToExceptions implements ExceptionFilter {
10
- private readonly logger = new Logger ( ApplyCorsToExceptions . name ) ;
11
15
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 > ( ) ;
29
18
19
+ if ( ! response . header ) {
30
20
return ;
31
21
}
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 ) ;
32
37
}
33
38
}
0 commit comments