Skip to content

Commit

Permalink
fix: cause last element index check
Browse files Browse the repository at this point in the history
  • Loading branch information
dmuharemagic authored and jsumners committed Nov 4, 2023
1 parent ceb6cde commit 7ea98d1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function createError (code, message, statusCode = 500, Base = Error) {
this.statusCode = statusCode

const lastElement = args.length - 1
if (lastElement !== 1 && args[lastElement] && typeof args[lastElement] === 'object' && 'cause' in args[lastElement]) {
if (lastElement !== -1 && args[lastElement] && typeof args[lastElement] === 'object' && 'cause' in args[lastElement]) {
this.cause = args.pop().cause
}

Expand Down
10 changes: 10 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ test('Create an error with cause', t => {
t.equal(err.cause, cause)
})

test('Create an error with cause and message', t => {
t.plan(2)
const cause = new Error('HEY')
const NewError = createError('CODE', 'Not available: %s')
const err = NewError('foo', { cause })

t.ok(err instanceof Error)
t.equal(err.cause, cause)
})

test('Create an error with last argument null', t => {
t.plan(2)
const cause = new Error('HEY')
Expand Down

0 comments on commit 7ea98d1

Please sign in to comment.