Skip to content

Commit

Permalink
stack: properly parse ErrnoException errors
Browse files Browse the repository at this point in the history
They have the code in the stack string in a weird way
  • Loading branch information
isaacs committed Sep 10, 2023
1 parent 5771c52 commit 2b0fb16
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/stack/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,12 +302,27 @@ export function captureString(
* contains `\n` and some lines after the first look like stack trace lines,
* incorrect data may result. It's only as good as the stack you pass to it.
*/
export const captureError = (e: Error): CallSiteLike[] => {
export const captureError = (
e: Error | NodeJS.ErrnoException
): CallSiteLike[] => {
// errors almost always have these fields
const { stack = '', message = '', name = '' } = e
const {
stack = '',
message = '',
name = '',
code,
} = e as NodeJS.ErrnoException
const head = name && message ? `${name}: ${message}\n` : ''
const errnoHead =
name && message && code ? `${name} [${code}]: ${message}` : ''
const cleanHead = !!head && stack.startsWith(head)
const s = cleanHead ? stack.substring(head.length) : stack
const cleanErrnoHead = !!errnoHead && stack.startsWith(errnoHead)

const s = cleanHead
? stack.substring(head.length)
: cleanErrnoHead
? stack.substring(errnoHead.length)
: stack
const cleaned = clean(
s
.trimEnd()
Expand Down
19 changes: 19 additions & 0 deletions src/stack/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,25 @@ ${short.stack?.split('\n').slice(1).join('\n')}`
t.end()
})

t.test('node errnoExceptions have coded messages', t => {
const er: NodeJS.ErrnoException = Object.assign(
new TypeError('blah'),
{
code: 'ERR_BLAH_DEE_BLOO',
}
)
er.stack = String(er.stack).replace(
/^TypeError:/,
'TypeError [ERR_BLAH_DEE_BLOO]:'
)
t.match(captureError(er)[0], {
lineNumber: Number,
columnNumber: Number,
fileName: String,
})
t.end()
})

t.end()
})
}

0 comments on commit 2b0fb16

Please sign in to comment.