Home  >  Q&A  >  body text

How to prevent further execution of Express middleware

I want to get this function if(thereIsSomeError) //Stop further execution. For example if some error occurs in middleware or callback then I don't want to execute callback (in app.route) and middleware further I tried this code. But I still think req.err is true. How can I solve this problem

// My MiddleWare
export let Middleware=()=> {
return (req,res,next)=>{
    next()
    console.log(req.err) // Problem is here.. i'm still getting req.err(true)
    if(!req.err){
        db.query(`query`,(error, responseData)=>{
            if(error) console.log(error)
            db.query(`second query`,{...// send data to the 
database})
        })
        }
    }
}



//End point    
app.post('/addStudent',Middleware, (req, res) => {
//setting error to true initially
    req.err=true;
    let data = req.body
    db.query(`query `, data.username, (err, d) => {
        if (err) return res.json(err)
        else {
        // since no Error accured so set the error to false
        req.err=false;
            let q = 'query';
            let values = {//data here}

            db.query(q, values, (err, data) => {
                if (err) return res.status(200).json(err)
                else return res.status(200).json({ data })
            })
        }
    })
})


P粉674999420P粉674999420291 days ago416

reply all(1)I'll reply

  • P粉198814372

    P粉1988143722024-01-03 10:40:23

    First of all, middleware runs before the request, not after. If you set req.err = true in the POST endpoint, it will remain TRUE, which means your database calls will definitely return an error.

    Second, to successfully abort the middleware call, use return. Returning a function immediately stops it. You can choose to return next(err) to forward the error to a handler, or use return res.send('Error') to terminate the response middleware.

    reply
    0
  • Cancelreply