API confirmation of success other than using response status

Viewed 232

So I am confused about industry-standard implementation. I feel this is a hacky way the way I am doing it right now

I want to display an error message whenever there is an actual error and display a failure message whenever the server return a nonsuccess status

The problem here is when there is an actual error on assignUser() it returns the error and this does not trigger the catch of the first function, so it is handled by the else statement instead and shows a failure message while it is an actual error. I tried to use throw new Error("error) in the catch of assignUser() but the same issue.

The second concern I have is regarding (200 >= status <300) is there a simpler way to check a successful operation other than checking the status which can be 200, 204 ...?

  try {
        let status = assignUser(user);
        if (status >= 200 && status < 300) {
          notify.show("message success");
        } else {
          notify.show("message failure");
        }
      } catch (e) {
        notify.show("message error");
      }


 export async function assignUser(user) {
  try {......
    return resp.status;
  } catch (e) {
    return e;
  }
}

1 Answers

I assume assignUser function is making an api call using fetch. So if you are not using the then catch method to resolve the promise, then the assignUser function has to be an async function.

async function assignUser(user) {
  try {
    const jsonRes = await fetch(url);
    if(!jsonRes.ok) {
       notify.show("message failure");
    } else {
       notify.show("message success");
       const result = await jsonRes.json();
       return result;
    }
  } catch (e) {
    notify.show("message error");
  }
}

Here you don't need another function to check the status and all and instead of checking with the status code you can use the response.ok property.

Hope this helps Thanks

Related