Using fetch, how to handle reject properly

347 Views Asked by At

I have the following function which came from the mern.io stack.

export default function callApi(endpoint, method = 'get', body) {
  return fetch(`${API_URL}/${endpoint}`, {
    headers: { 'content-type': 'application/json' },
    method,
    body: JSON.stringify(body),
  })
  .then(response => response.json().then(json => ({ json, response })))
  .then(({ json, response }) => {
    if (!response.ok) {
      return Promise.reject(json);
    }
    return json;
  })
  .then(
    response => response,
    error => error
  );
}

I call the function the following way

callApi('auth/register', 'post', {
      username,
      password,
}).then(function(res) {
    // do stuff
});

The response will either be a 201 or a 422. How can handle the 422 the proper way? A 422 would occur if a username already exists.

Do I put all the logic in the first then such as the following:

callApi('auth/register', 'post', {
      username,
      password,
}).then(function(res) {
    if (res.error) {

    } else {
    }
});
1

There are 1 best solutions below

2
On

Assuming callApi returns a Promise object:

callApi('auth/register', 'post', {
      username,
      password,
}).then(function(res) {
    // res
}).catch(function(err) {
    // handle err
});

For more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise