diff --git a/index.js b/index.js index 3911f6f..257cd7c 100644 --- a/index.js +++ b/index.js @@ -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 } diff --git a/test/index.test.js b/test/index.test.js index 7bd813e..2fabd6f 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -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')