Ash Rhazaly
Ash Rhazaly

Reputation: 215

Using a .catch instead of try/catch block

Instead of using a traditional try/catch to handle errors when sending requests like below

let body;
try {
    const response = await sendRequest(
        "POST",
        "/api/AccountApi/RefundGetStatus",
        JSON.stringify(refundParams),
        undefined,
        headers
    );
    body = response.body;
} catch (error) {
    log("error", "An error occurred sending a request", { error });
    throw createError("An error has occurred", DefaultErrors.API_ERROR);
}

I was thinking if it's possible to achieve the same result rewriting the error handling like below.

const response = await sendRequest(
    "POST",
    "/api/AccountApi/RefundGetStatus",
    JSON.stringify(refundParams),
    undefined,
    headers
).catch((err: any) => {
    log("error", "An error occurred sending a request", { err });
    throw createError("An error has occurred", DefaultErrors.API_ERROR);
});

Would the above code block be able to handle undefined errors and perhaps JSON.parse errors ?

Upvotes: 0

Views: 390

Answers (1)

Alex W
Alex W

Reputation: 176

You can use both

try { 
  await sendRequest()
} catch (err) {
  // do something
}

or

sendRequest().catch(err => { // do something})

to catch an error.

Below is a simple example, you can paste it to typescript playgound to give it a try.

const sendRequest = (str: string) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('get response');
      reject('error message');
    }, 2000)
  })
}

const test1 = async ()=> {
  try{
    await sendRequest('data');
  } catch (err) {
    // will print 'err===> error message'
    console.log('err===>', err)
  }
}

const test2 = async ()=> {
  sendRequest('data').catch(err => {
    // will print 'err===> error message'
    console.log('err=====>', err)
  })
}

test1();
test2();

test1() and test2() will both catch the error.

Upvotes: 2

Related Questions