0

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?

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • [That's the way it's intended to work.](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) – Pointy Jun 06 '19 at 15:24

1 Answers1

2

catch is intended for when your code has errors or something prevented your code from executing/fulfilling. In case of fetch those conditions would be a blocked port, network failure, server resets connection or anything which did not let your request be completed. A server returning 400 is not a code error. The request was fulfilled. A response was given. You just didn't get the data you were expecting. It's a logic error.

So you'll have to check for 400/500 errors in your code manually.

To given an analogy, imagine you are trying to read a file by fs.readFile('test.json',(err,data) => console.log(data)). If data is empty, it is not an error. The code read the file and there was just nothing to report. If data is garbled, it's not an error. Maybe it's an encoding issue and you are parsing the content incorrectly. An error would be that the file is locked by another process, permissions are denied, the file doesn't exist etc.

suv
  • 1,373
  • 1
  • 10
  • 18