Error Handling

Thrown errors are a good thing! They mean the runtime has successfully
identified when something in your program has gone wrong and it’s letting
you know by stopping function execution on the current stack, killing the
process (in Node), and notifying you in the console with a stack trace.

Don’t ignore caught errors

Doing nothing with a caught error doesn’t give you the ability to ever fix
or react to said error. Logging the error to the console (console.log)
isn’t much better as often times it can get lost in a sea of things printed
to the console. If you wrap any bit of code in a try/catch it means you
think an error may occur there and therefore you should have a plan,
or create a code path, for when it occurs.

Bad:

  1. try {
  2. functionThatMightThrow();
  3. } catch (error) {
  4. console.log(error);
  5. }

Good:

  1. try {
  2. functionThatMightThrow();
  3. } catch (error) {
  4. // One option (more noisy than console.log):
  5. console.error(error);
  6. // Another option:
  7. notifyUserOfError(error);
  8. // Another option:
  9. reportErrorToService(error);
  10. // OR do all three!
  11. }

Don’t ignore rejected promises

For the same reason you shouldn’t ignore caught errors
from try/catch.

Bad:

  1. getdata()
  2. .then((data) => {
  3. functionThatMightThrow(data);
  4. })
  5. .catch((error) => {
  6. console.log(error);
  7. });

Good:

  1. getdata()
  2. .then((data) => {
  3. functionThatMightThrow(data);
  4. })
  5. .catch((error) => {
  6. // One option (more noisy than console.log):
  7. console.error(error);
  8. // Another option:
  9. notifyUserOfError(error);
  10. // Another option:
  11. reportErrorToService(error);
  12. // OR do all three!
  13. });