M
M
Michael2018-07-14 23:43:28
Node.js
Michael, 2018-07-14 23:43:28

What is the best way to handle errors in a class method?

Hello. I have a class with two methods. At the moment, I handle errors like this:

class Geo {
   async method() {
      try {
          return await _method()
      } catch (err) {
          throw err
      }
   }

   async _method() {
      try {
         return await someFunc()
      } catch (err) {
         throw err
      }
   }
}

app.post('/test', async (req, res) => {
  try {
     const geo = new Geo()
     geo.method()
  } catch (err) {
     console.log(err)
  }
})

Do I understand correctly that I can remove try/catch from Geo class methods? After all, if I wrap a call to geo.method () in try / catch, then everything will work the same way. Otherwise, I don’t want to fence redundant try / catch everywhere

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-15
@mak_ufo

1. Design:

try {
  // что угодно
} catch (err) {
  throw err;
}

doesn't make sense. Because it is equivalent to:
2. Using an asynchronous function with only one return:
async method() {
  return await _method();
}

just as pointless and the code can be simplified to:
method() {
  return  _method();
}

3. "fencing redundant try/catch everywhere" is wrong because:
const foo = () => {
  try {
    bar();
  } catch (e) {
    // этот блок не будет вызван никогда, так как ошибка перехватывается в вызове bar()
  }
};

const bar = () => {
  try {
    dangerousCall();
  } catch (e) {
    // этот блок будет вызван в случае ошибки вызова dangerousCall()
  }
}

try {
  foo();
} catch (e) {
  // этот блок не будет вызван никогда, так как ошибка перехватывается в вызове bar()
}

Demo
4. Handle the error where the function that can trigger it is executed.
No, that would be the wrong decision. See point 4.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question