D. Rattansingh
D. Rattansingh

Reputation: 1669

throwing error message in router async middleware

This is my router:

router.post('/post', isAccess, controller.create)

IsAccess middleware:

exports.isAccess=(request, result, next)=>{

    const userid='64c1248482bcfbb533b366d5'
    User.findOne({_id:userid}).select({role:1}).then(user=>{
        if(!role==='routerRoleResource'))
            { const error=new Error('Authorization failed'); error.status=401; throw error }
    }).
    catch(err=>{
        if(!err.statusCode) err.statusCode=500;
        next(err)
    })
    next()
}

Although its generating an error in the console, it's not stopping the processing in the route and controller.create is still being called. It I remove the catch and have just this, I'm getting the following error:

exports.isAccess=(request, result, next)=>{

    const userid='64c1248482bcfbb533b366d5'
    User.findOne({_id:userid}).select({role:1}).then(user=>{
        if(!role==='routerRoleResource'))
            { const error=new Error('Authorization failed'); error.status=401; throw error }
    })
    next()
}

enter image description here

I tried using async await but getting the same issue. However if I have the following:

exports.isAccess=(request, result, next)=>{    
    const error=new Error('Authorization failed'); 
    error.status=401; 
    throw error
    next()
}

It's working perfectly in postman:

enter image description here

However if I just put the async keyword ( exports.isAccess=async(request, result, next) ) it stops working and generate error. For some reason the error module is not working with async or promises. Anyone could point me in correct direction?

Upvotes: 0

Views: 45

Answers (0)

Related Questions