I'm using node-fetch to make a call from one API to another one, however when an error occurs in "API 2", the success callback runs.
I'm not sure if this is intended behaviour or not and if you're supposed to check the response for a status code rather than having the catch
callback run.
API 1:
fetch('http://localhost:4060/api/passwords', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: doc._id,
hash: hash
})
})
.then((response) => {
console.log(response);
return res.json(doc);
})
.catch((e) => {
console.log('ERROR')
next(e);
});
API 2:
app.use((err, req, res, next) => {
res.status(err.status).json({
message: err.isPublic ? err.message : httpStatus[err.status],
stack: config.env === 'development' ? err.stack : {}
});
});
When there is an error in "API 2" the response looks like this:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'http://localhost:4060/api/passwords',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object] },
counter: 0 } }
As you can see there was an error, and the snippet from API 2 ran, returning the error with a 400
status code.
As mentioned above, is this intended behaviour? I was under the impression that catch
should run instead of then
, is there any way I can tweak my code for this to happen?