fastify-mongodb is "eating" errors on register
barenko opened this issue · comments
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure it has not already been reported
Fastify version
3.20.2
Plugin version
4.1.0
Node.js version
4.1.0
Operating system
Linux
Operating system version (i.e. 20.04, 11.3, 10)
Manjaro 21.1.1
Description
When there is some error on fastify-mongodb configuration (uri error), the error is not throw and the fastify-autoload does not load the paths.
Steps to Reproduce
structure:
src/app.js
src/services/health.js
app.js
const fastify = require('fastify')({ logger: true })
const path = require('path')
//HERE: I 'forget' the configuration...
//NOTICE: To see the autoloader works, just comment this line:
fastify.register(require('fastify-mongodb'))
//HERE: this was registered :)
fastify.get('/hello', async (request, reply) => {
return { hello: 'world' }
})
//HERE: this load no file :(
fastify.register(require('fastify-autoload'), {
dir: path.join(__dirname, 'services'),
options: { prefix: '/api' },
ignorePattern: /.*(test|spec).js/
})
fastify.ready(() => {
console.log('Routes\n' + fastify.printRoutes())
})
const start = async () => {
try {
await fastify.listen(3000)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
health.js
'use strict'
module.exports = async function (fastify, opts) {
fastify.get('/', async function (request, reply) {
try {
let stats = await fastify.mongo.db.stats()
if (stats.ok) {
reply.send({ message: 'OK' })
} else {
reply.status(500).send({ message: 'NOK' })
}
} catch (e) {
reply.status(500).send({ message: 'NOK', error: e.message })
}
})
}
module.exports.autoPrefix = '/health'
start the server node src/app.js
and the output will be:
$ node src/app.js
Routes
└── /hello (GET)
{"level":30,"time":1630624706482,"pid":10021,"hostname":"barenko-virtualbox","msg":"Server listening at http://127.0.0.1:3000"}
Expected Behavior
$ node src/app.js
Routes
└── /
├── hello (GET)
└── api
├── /health (GET)
└── / (GET)
{"level":30,"time":1630624488203,"pid":9675,"hostname":"barenko-virtualbox","msg":"Server listening at http://127.0.0.1:3000"}
You need to manage the error when you use .ready
:
const fastify = require('fastify')({ logger: true })
fastify.register(async function plugin (instance, opts) {
throw new Error('')
})
fastify.ready((err) => {
console.log({ err }) // the error is ignored here
})
fastify.listen(8080)
https://www.fastify.io/docs/latest/Server/#ready
To print the routes I would suggest using the onReady
hook instead
https://www.fastify.io/docs/latest/Hooks/#onready