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,23 @@ 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 > ( ) ;
16
+ const ctx = host . switchToHttp ( ) ;
17
+ const response = ctx . getResponse < Response > ( ) ;
15
18
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
- ) ;
19
+ response . header ( 'Access-Control-Allow-Origin' , '*' ) ;
20
+ response . header (
21
+ 'Access-Control-Allow-Methods' ,
22
+ 'GET,HEAD,PUT,PATCH,POST,DELETE' ,
23
+ ) ;
24
+ response . header (
25
+ 'Access-Control-Allow-Headers' ,
26
+ 'Origin, X-Requested-With, Content-Type, Accept' ,
27
+ ) ;
25
28
26
- response . status ( exception . getStatus ( ) ) . json ( exception . response ) ;
27
- } catch ( e ) {
28
- this . logger . error ( e ) ;
29
+ const status =
30
+ exception instanceof HttpException ? exception . getStatus ( ) : 500 ;
29
31
30
- return ;
31
- }
32
+ response . status ( status ) . json ( exception . response ) ;
32
33
}
33
34
}
0 commit comments