Express Error Handling: Sending a Message to Frontend

Viewed 2473

I'm having some trouble error handling my authentication API calls. When I send the 500 status from Express, my frontend (Vue in this case) only picks up the message Request failed with status code 500 rather than something more helpful for triage like this is the worst error ever (in the example below).

In the below example, when I call '/post' from the API, I throw an error which is handled by my custom middleware. The middleware successfully handles the error and sends the appropriate status to my frontend, but I can't figure out how to send useful messages (e.g. 'this is the worst error ever') / access them in the front end.

Is this a common use case? Am I doing anything obviously wrong? Does the message I send come up in the (err) parameter, or do I need to add a resp parameter?

Express Route for '/login'

router.post('/login', (req, res, next) => {
    throw Error('this is the worst error ever')
})

Custom express error handler

app.use(function(err, req, res, next) {
    res.status(err.status || 500).send({
        error: {
            status: err.status || 500,
            message: err.message || 'Internal Server Error',
        },
    });
});

Handle the API Response in Vue

login (e) {
    e.preventDefault();
    UserService.login(this.username, this.password) //this is simple axios post call 
    .catch((err) => {
         this.loginStatus = err.message
         return
    })
}
2 Answers

Found the answer to this for those that find this helpful. The err that is caught has a response variable. This is where the data is sent via the express send command. See corrected code below for the frontend:

login (e) {
    e.preventDefault();
    UserService.login(this.username, this.password) //this is simple axios post call 
    .catch((err) => {
         this.loginStatus = err.response.data.message
         return
    })
}

I think you need to add:

Throw new Error()

instead of

Throw Error

If you are making an asynchronous calling you can do this

app.get('/', function (req, res, next) {
  fs.readFile('/file-does-not-exist', function (err, data) {
    if (err) {
       next(err) // Pass errors to Express.
    } else {
       res.send(data)
    }
  })
})

Code should look like this:

router.post('/login', (req, res, next) => {
   throw new Error('this is the worst error ever')
})

Check this in express documentation

Related