After sending an axios request to my Node server, how can I respond where I "reject" the Axios route/request and end up in the "catch()" of my client side code? I know "res.send(data)" or "res.json(data)" will resolve into "then()" of the promise. Is there anything I can respond with that will reject it?
axios.post('/edit-item', {_id: id, updateText: editInput.value, author: author}).then((response) => {
e.target.parentElement.parentElement.children[3].innerHTML = `${response.data}`
}).catch(() => {
//I want to end up here by responding with something from the server
})
You can raise an error in Node.js which will be handled by the internal error handler, or you may return the status code of your choice
Raising an error:
app.post(req, res, next) {
throw new Error('Something went wrong')
Returning error message:
app.post(req, res, next) {
res.status(500).send({ error: 'Something failed!' })
}
instead of 500 you can enter any error status code there
Once you return an error code, axios will go into the catch section
You can find more about error handling here: error handling
Return anything with http status code not in range status >= 200 && status < 300 from your server will get you in the .catch block by default:
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}
https://axios-http.com/docs/handling_errors
You can override validateStatus to define in which cases the axios Promise is resolved/rejected