-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
base-ws-exception-filter.ts
61 lines (53 loc) · 1.58 KB
/
base-ws-exception-filter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { ArgumentsHost, Logger, WsExceptionFilter } from '@nestjs/common';
import { isObject } from '@nestjs/common/utils/shared.utils';
import { MESSAGES } from '@nestjs/core/constants';
import { WsException } from '../errors/ws-exception';
/**
* @publicApi
*/
export class BaseWsExceptionFilter<TError = any>
implements WsExceptionFilter<TError>
{
private static readonly logger = new Logger('WsExceptionsHandler');
public catch(exception: TError, host: ArgumentsHost) {
const client = host.switchToWs().getClient();
this.handleError(client, exception);
}
public handleError<TClient extends { emit: Function }>(
client: TClient,
exception: TError,
) {
if (!(exception instanceof WsException)) {
return this.handleUnknownError(exception, client);
}
const status = 'error';
const result = exception.getError();
const message = isObject(result)
? result
: {
status,
message: result,
};
client.emit('exception', message);
}
public handleUnknownError<TClient extends { emit: Function }>(
exception: TError,
client: TClient,
) {
const status = 'error';
client.emit('exception', {
status,
message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE,
});
if (this.isExceptionObject(exception)) {
return BaseWsExceptionFilter.logger.error(
exception.message,
exception.stack,
);
}
return BaseWsExceptionFilter.logger.error(exception);
}
public isExceptionObject(err: any): err is Error {
return isObject(err) && !!(err as Error).message;
}
}