Welcome to the Linux Foundation Forum!

ch5 throw notFound() is not defined

fastify.get('/:id', async (request, reply) => {
    const { id } = request.params
    try {
      return await read(id)
    } catch (err) {
      if (err.message === 'not found') throw notFound()
      throw err
    }
  })

Does not work anymore. it return that err

"err": {
    "type": "ReferenceError",
    "message": "notFound is not defined",

I found this fix on the web: https://github.com/fastify/fastify/issues/402

const { NotFound } = require('http-errors')

module.exports = async(fastify, opts) => {
    fastify.get('/:id', async(request, reply) => {
        const { id } = request.params
        try{
            const d = await promisify(bicycle.read)(id)
            reply.send(d)
        } catch(e) {
            console.log('the errrrrrrrr: ', e.message)
            if(e.message === 'not found') throw new NotFound()
            // if(e.message === 'not found') throw notFound()
            else throw e
        }
    })
}

Comments

  • hi @djedje the material talks about using fastify-sensible - this supplies the http-errors notFound method on the reply object. If you skipped the fastify-sensible step (or otherwise removed it, since the new create-fastify project now includes it, then you would hit the notFound is not defined error.

Categories

Upcoming Training