Handling errors: best practices?

Charles Loder - Aug 26 '22 - - Dev Community

I'll often find myself having to handle a few api calls, and I'm not really sure what the best error handling practices are.

Below is an example of a pattern I find myself writing a lot — treating throws like returns and allowing the errors to "bubble up."

Generally, it works for me, but I'm not sure if there is a better way to handle them. Or some standard practices.

Any advice or thoughts would be appreciated!

async function someApiReq(id) {
  try {
    const resp = fetch('https://foo.com/api' { body: JSON.stringify(id) });
    if(!resp.ok) throw resp;
    return await resp.json().data
  } catch(e) {
    if(e instanceof ApiError) {
      throw e.apiMessage
    }
    throw e
  }
}

async function someOtherApiReq(id) {
  try {
    const resp = fetch('https://bar.com/api' { body: JSON.stringify(id) });
    if(!resp.ok) throw resp;
    return await resp.json().data
  } catch(e) {
    throw e
  }
}

(async () => {
  try {
    const id = 1;
    const data = someApiReq(id);
    const otherData = someOtherApiReq(data.id);
    console.log(otherData);
  } catch(e) {
    console.error(e)
  }
})();
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player