Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-throwing exception on catch to upper level on async function

Throwing error to upper level in an async function

This

async create(body: NewDevice, firstTry = true): Promise<RepresentationalDevice> {
  try {
    return await this.dataAccess.getAccessToken()
  } catch (error) {
    throw error
  }
}

VS this

async create(body: NewDevice, firstTry = true): Promise<RepresentationalDevice> {
  return await this.dataAccess.getAccessToken()
}

I mean at the end on the upper level I must catch the error anyway and there is no modifications at all on the catch

Are these two approaches identical? Can I use the second approach without error handling issues?

like image 279
Iván Sánchez Avatar asked Nov 07 '22 17:11

Iván Sánchez


1 Answers

This has nothing to do with async functions. Catching an error just to rethrow it is the same as not catching it in the first place. I.e.

try {
  foo();
} catch(e) {
  throw e;
}

and

foo();

are basically equivalent, except that the stack trace might be different (since in the first case the error is thrown at a different location).

like image 200
2 revs Avatar answered Nov 14 '22 21:11

2 revs