|
| 1 | +import * as util from 'node:util'; |
| 2 | +import { defineIntegration } from '@sentry/core'; |
| 3 | + |
| 4 | +const INTEGRATION_NAME = 'NodeSystemError'; |
| 5 | + |
| 6 | +type SystemErrorContext = { |
| 7 | + dest?: string; // If present, the file path destination when reporting a file system error |
| 8 | + errno: number; // The system-provided error number |
| 9 | + path?: string; // If present, the file path when reporting a file system error |
| 10 | +}; |
| 11 | + |
| 12 | +type SystemError = Error & SystemErrorContext; |
| 13 | + |
| 14 | +function isSystemError(error: unknown): error is SystemError { |
| 15 | + if (!(error instanceof Error)) { |
| 16 | + return false; |
| 17 | + } |
| 18 | + |
| 19 | + if (!('errno' in error) || typeof error.errno !== 'number') { |
| 20 | + return false; |
| 21 | + } |
| 22 | + |
| 23 | + // Appears this is the recommended way to check for Node.js SystemError |
| 24 | + // https://github.com/nodejs/node/issues/46869 |
| 25 | + return util.getSystemErrorMap().has(error.errno); |
| 26 | +} |
| 27 | + |
| 28 | +type Options = { |
| 29 | + /** |
| 30 | + * If true, includes the `path` and `dest` properties in the error context. |
| 31 | + */ |
| 32 | + includePaths?: boolean; |
| 33 | +}; |
| 34 | + |
| 35 | +/** |
| 36 | + * Captures context for Node.js SystemError errors. |
| 37 | + */ |
| 38 | +export const systemErrorIntegration = defineIntegration((options: Options = {}) => { |
| 39 | + return { |
| 40 | + name: INTEGRATION_NAME, |
| 41 | + processEvent: (event, hint, client) => { |
| 42 | + if (!isSystemError(hint.originalException)) { |
| 43 | + return event; |
| 44 | + } |
| 45 | + |
| 46 | + const error = hint.originalException; |
| 47 | + |
| 48 | + const errorContext: SystemErrorContext = { |
| 49 | + ...error, |
| 50 | + }; |
| 51 | + |
| 52 | + if (!client.getOptions().sendDefaultPii && options.includePaths !== true) { |
| 53 | + delete errorContext.path; |
| 54 | + delete errorContext.dest; |
| 55 | + } |
| 56 | + |
| 57 | + event.contexts = { |
| 58 | + ...event.contexts, |
| 59 | + node_system_error: errorContext, |
| 60 | + }; |
| 61 | + |
| 62 | + for (const exception of event.exception?.values || []) { |
| 63 | + if (exception.value) { |
| 64 | + if (error.path && exception.value.includes(error.path)) { |
| 65 | + exception.value = exception.value.replace(`'${error.path}'`, '').trim(); |
| 66 | + } |
| 67 | + if (error.dest && exception.value.includes(error.dest)) { |
| 68 | + exception.value = exception.value.replace(`'${error.dest}'`, '').trim(); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return event; |
| 74 | + }, |
| 75 | + }; |
| 76 | +}); |
0 commit comments