-
Notifications
You must be signed in to change notification settings - Fork 368
/
error.manager.ts
184 lines (161 loc) · 7.08 KB
/
error.manager.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import * as uuid from 'uuid';
import type { EventHint } from '@sentry/node';
import sentry from '@sentry/node';
import type { Tracer } from 'dd-trace';
import type { ErrorEvent } from '@sentry/types';
import logger from '../logger/console.js';
import { NangoError } from './error.js';
import type { Response, Request } from 'express';
import { isCloud, getEnvironmentId, getAccountIdAndEnvironmentIdFromSession, isApiAuthenticated, isUserAuthenticated, packageJsonFile } from './utils.js';
import environmentService from '../services/environment.service.js';
import accountService from '../services/account.service.js';
import userService from '../services/user.service.js';
export enum ErrorSourceEnum {
PLATFORM = 'platform',
CUSTOMER = 'customer'
}
export type ErrorSource = ErrorSourceEnum;
interface ErrorOptionalConfig {
source: ErrorSource;
accountId?: number;
userId?: number;
environmentId?: number;
metadata?: Record<string, unknown>;
operation?: string;
}
class ErrorManager {
constructor() {
try {
if (isCloud() && process.env['SENTRY_DNS']) {
const packageVersion = packageJsonFile().version;
sentry.init({
dsn: process.env['SENTRY_DNS'],
beforeSend(event: ErrorEvent, _: EventHint) {
return event.user?.id === 'account-78' ? null : event;
},
environment: process.env['NODE_ENV'] as string,
release: 'nango@' + packageVersion
});
}
} catch (_) {
return;
}
}
public report(e: unknown, config: ErrorOptionalConfig = { source: ErrorSourceEnum.PLATFORM }, tracer?: Tracer): void {
sentry.withScope(async function (scope) {
if (config.environmentId || config.accountId) {
let accountId: number | undefined;
if (config.environmentId) {
const environmentName = await environmentService.getEnvironmentName(config.environmentId);
accountId = (await environmentService.getAccountIdFromEnvironment(config.environmentId)) as number;
sentry.setTag('environmentName', environmentName);
}
if (config.accountId && !config.environmentId) {
accountId = config.accountId;
}
const account = await accountService.getAccountById(accountId as number);
if (!config.userId) {
const users = await userService.getUsersByAccountId(accountId as number);
sentry.setUser({
id: `account-${accountId}`,
organization: account?.name || '',
emails: users.map((user) => user.email).join(','),
userIds: users.map((user) => user.id).join(',')
});
}
}
if (config.userId) {
const user = await userService.getUserById(config.userId);
sentry.setUser({
id: `user-${config.userId}`,
email: user?.email || '',
userId: user?.id
});
}
sentry.setTag('source', config.source);
if (config.operation) {
sentry.setTag('operation', config.operation);
}
if (config.metadata) {
const metadata = Object.entries(config.metadata).reduce(
(acc, [key, value]) => {
if (typeof value === 'object') {
acc[key] = JSON.stringify(value);
} else {
acc[key] = value;
}
return acc;
},
{} as Record<string, unknown>
);
scope.setContext('metadata', metadata);
}
if (typeof e === 'string') {
sentry.captureException(new Error(e));
} else {
sentry.captureException(e);
}
});
logger.error(`Exception caught: ${JSON.stringify(e, Object.getOwnPropertyNames(e))}`);
if (e instanceof Error && tracer) {
// Log to datadog manually
// https://github.com/DataDog/dd-trace-js/issues/1944
const span = tracer.scope().active();
if (span) {
span.setTag('error', e);
}
}
}
public errResFromNangoErr(res: Response, err: NangoError | null) {
if (err) {
logger.error(`Response error: ${JSON.stringify({ statusCode: err.status, type: err.type, payload: err.payload, message: err.message })}`);
if (!err.message) {
res.status(err.status || 500).send({ type: err.type, payload: err.payload });
} else {
res.status(err.status || 500).send({ error: err.message, type: err.type, payload: err.payload });
}
}
}
public errRes(res: any, type: string) {
const err = new NangoError(type);
this.errResFromNangoErr(res, err);
}
public async handleGenericError(err: any, req: Request, res: any, tracer: Tracer): Promise<void> {
const errorId = uuid.v4();
if (!(err instanceof Error)) {
err = new NangoError('generic_error_malformed', errorId);
} else if (!(err instanceof NangoError)) {
err = new NangoError(err.message, errorId);
}
const nangoErr: NangoError = err;
if (isApiAuthenticated(res)) {
const environmentId = getEnvironmentId(res);
this.report(nangoErr, { source: ErrorSourceEnum.PLATFORM, environmentId, metadata: err.payload }, tracer);
} else if (isUserAuthenticated(req)) {
const { response, success, error } = await getAccountIdAndEnvironmentIdFromSession(req);
if (!success || response === null) {
this.report(error, { source: ErrorSourceEnum.PLATFORM, metadata: err.payload }, tracer);
} else {
const { environmentId } = response;
this.report(nangoErr, { source: ErrorSourceEnum.PLATFORM, environmentId, metadata: err.payload }, tracer);
}
} else {
this.report(nangoErr, { source: ErrorSourceEnum.PLATFORM, metadata: err.payload }, tracer);
}
const supportError = new NangoError('generic_error_support', errorId);
this.errResFromNangoErr(res, supportError);
}
public getExpressRequestContext(req: Request): Record<string, unknown> {
const metadata: Record<string, unknown> = {};
metadata['baseUrl'] = req.baseUrl;
metadata['originalUrl'] = req.originalUrl;
metadata['subdomains'] = req.subdomains;
metadata['body'] = req.body;
metadata['hostname'] = req.hostname;
metadata['method'] = req.method;
metadata['params'] = req.params;
metadata['query'] = req.query;
return metadata;
}
}
export default new ErrorManager();