-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall-exceptions.ts
70 lines (63 loc) · 2.35 KB
/
all-exceptions.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
62
63
64
65
66
67
68
69
70
import { existsSync, mkdirSync, appendFile } from 'fs';
import * as path from 'path';
import { Catch, ArgumentsHost, Logger } from '@nestjs/common';
import { GqlArgumentsHost, GqlExceptionFilter } from '@nestjs/graphql';
import { GraphQLError } from 'graphql';
import { promisify } from 'util';
const mkdir = promisify(mkdirSync);
const append = promisify(appendFile);
@Catch()
export class GqlAllExceptionsFilter implements GqlExceptionFilter {
private readonly logger = new Logger(GqlAllExceptionsFilter.name);
private logFilePath = path.join(`logs/${new Date().getFullYear()}/${new Date().getMonth()+1}/${new Date().getDate()}.log`);
private async logToFile(message: string) {
const logMessage = `${new Date().toISOString()} - ${message}\n`;
// Check if the log file exists, and create it if it doesn't
if (!existsSync(this.logFilePath)) {
const logsDirectory = path.dirname(this.logFilePath);
try {
mkdir(logsDirectory, { recursive: true });
} catch (error) {
console.error(`Failed to create logs directory: ${error}`);
}
}
await append(this.logFilePath, logMessage);
}
catch(exception: unknown, host: ArgumentsHost) {
const gqlHost = GqlArgumentsHost.create(host);
const context = gqlHost.getContext();
const response = context?.res;
let status = 500;
let message = 'Internal Server Error';
let messageCode = 0;
let stacktrace = [];
if (exception instanceof GraphQLError) {
message = exception.message;
stacktrace = exception.stack?.split('\n') || [];
status = exception.extensions?.status || (500 as any);
messageCode = exception.extensions?.messageCode as any;
} else if (exception instanceof Error) {
status = 'status' in exception ? exception['status'] : (500 as any);
message = exception.message;
stacktrace = exception.stack?.split('\n') || [] as any;
} else {
this.logger.error('Unexpected error', exception);
}
if (response) {
response.status(status).json({
errors: [
{
message,
extensions: {
messageCode,
stacktrace,
},
},
],
data: null,
});
}
const logOutput = `Error: ${message} Status: ${status} messageCode: ${messageCode} stacktrace: ${stacktrace}`;
this.logToFile(logOutput);
}
}