Skip to content

Commit

Permalink
fix: Improve error message for hooks check (#4387)
Browse files Browse the repository at this point in the history
* Improve error message for hooks check

* log null value more precisely

* final update and all testcase passed
  • Loading branch information
debadutta98 committed Oct 31, 2022
1 parent e9604ce commit a71dd83
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion lib/hooks.js
Expand Up @@ -52,7 +52,7 @@ Hooks.prototype.validate = function (hook, fn) {
if (supportedHooks.indexOf(hook) === -1) {
throw new Error(`${hook} hook not supported!`)
}
if (typeof fn !== 'function') throw new FST_ERR_HOOK_INVALID_HANDLER(hook, typeof fn)
if (typeof fn !== 'function') throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(fn))
}

Hooks.prototype.add = function (hook, fn) {
Expand Down
4 changes: 2 additions & 2 deletions lib/route.js
Expand Up @@ -249,11 +249,11 @@ function buildRouting (options) {
if (Array.isArray(opts[hook])) {
for (const func of opts[hook]) {
if (typeof func !== 'function') {
throw new FST_ERR_HOOK_INVALID_HANDLER(hook, typeof func)
throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(func))
}
}
} else if (opts[hook] !== undefined && typeof opts[hook] !== 'function') {
throw new FST_ERR_HOOK_INVALID_HANDLER(hook, typeof opts[hook])
throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(opts[hook]))
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions test/hooks.test.js
Expand Up @@ -3332,7 +3332,7 @@ test('registering invalid hooks should throw an error', async t => {
return 'hello world'
}
})
}, new Error('onRequest hook should be a function, instead got undefined'))
}, new Error('onRequest hook should be a function, instead got [object Undefined]'))

t.throws(() => {
fastify.route({
Expand All @@ -3343,7 +3343,7 @@ test('registering invalid hooks should throw an error', async t => {
return 'hello world'
}
})
}, new Error('onRequest hook should be a function, instead got object'))
}, new Error('onRequest hook should be a function, instead got [object Null]'))

// undefined is ok
fastify.route({
Expand All @@ -3363,5 +3363,5 @@ test('registering invalid hooks should throw an error', async t => {
fastify.get('/', function (request, reply) {
reply.send('hello world')
})
}, new Error('onSend hook should be a function, instead got undefined'))
}, new Error('onSend hook should be a function, instead got [object Undefined]'))
})
2 changes: 1 addition & 1 deletion test/internals/hooks.test.js
Expand Up @@ -78,6 +78,6 @@ test('should throw on wrong parameters', t => {
t.fail()
} catch (e) {
t.equal(e.code, 'FST_ERR_HOOK_INVALID_HANDLER')
t.equal(e.message, 'onSend hook should be a function, instead got object')
t.equal(e.message, 'onSend hook should be a function, instead got [object Null]')
}
})

0 comments on commit a71dd83

Please sign in to comment.