I'm trying to send an error response from and express api call that has an error when a user adds a non-unique category or no category at all. I'm able to save the category to the DB and send back a proper response. I'm not sure I'm using the correct response method in express.
Express:
exports.addCategory = (req, res, next) => {
var category = new Category(req.body);
category.save().then(doc => {
res.send(doc);
}).catch(err => {
res.send({message:'Category must be unique!'});
});
}
React
export function addCategoryName( name ){
return (dispatch) => {
const dbPost = axios.post('/api/add-category', {name:name});
dbPost.then(result => {
console.log("result = ", result);
dispatch({
type: type.ADD_CATEGORY_NAME,
payload: result.data
});
}).catch(err => {
console.log("CATCH = ", err);
// dispatch({
// type: type.ADD_CATEGORY_NAME_ERROR,
// payload: err.message
// });
});
}
}
The above response goes straight to the dbPost.then(result => { instead of the catch. So I tried
Express response
res.status(err.statusCode || 500).json({message:msg});
This gave me:
CATCH = Error: Request failed with status code 500
at createError (createError.js:15)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
All i'm trying to do is respond with an error message from express and for my axios promise to catch it as an error. But I can't seem to get to the error message. Is there something I'm missing in express as a response for this.