0

I am having trouble with some basic error handling/catching. If I have the following code:

function test() {
    areThereErrors(sum(1,2));
    areThereErrors(sumo(1,2));
}

function areThereErrors(value) {
    console.log(value);
}

How do I go about catching the error from the typo in the second call to areThereErrors? My basic understanding is that I have to call test() but unfortunately I only console.log 3 once and that's it. I want to be able to return true if sumo throws an error because sumo isn't a function.

NOTE: The crux of the issue is, is it possible to catch the error with code WITHIN areThereErrors?

6
  • The problem is that sumo won't throw an error because it is not a function and thus never called. Instead, test() will throw the error so that's also the location in which you'd need to catch the error Commented Mar 14, 2016 at 18:03
  • Take a look at try and catch. Commented Mar 14, 2016 at 18:03
  • 1
    @burnedikt sumo will indeed throw an error (a ReferenceError) when the attempt is made to call it. Commented Mar 14, 2016 at 18:03
  • I have used try and catch plenty of times. My issue comes in that the error seems to get thrown when you invoke test rather than when you invoke areThereErrors(sumo(1,2)) Commented Mar 14, 2016 at 18:06
  • 1
    sumo(1,2) is executed before passing its returned value into areThereErrors. Commented Mar 14, 2016 at 18:13

2 Answers 2

1

The crux of the issue is, is it possible to catch the error with code WITHIN areThereErrors?

No, because the error will be thrown when the parameters to areThereErrors are evaluated in preparation to calling it, and it will never be called.

However, you could make areThereErrors work in the way you seem to want to by passing it a function to be executed.

function areThereErrors(fn) {
  try { console.log(fn()); }
  catch (e) { console.log("Oh, no, an error has been thrown"); return true; }
}

Now you can write your code as

function test() {
    areThereErrors(() => sum(1,2)));
    areThereErrors(() => sumo(1,2)));
}

Another alternative is to make areThereErrors into a higher-order function which takes one function as input and returns another function which wraps a call to it in try/catch. The approach would be:

function areThereErrors(fn) {
  return function() {
    try {
      return fn(...arguments);
    } catch (e) {
      return false;
    }
  };
}

Now you can write code such as

function test() {
    areThereErrors(sum)(1, 2);
    areThereErrors(sumo)(1, 2);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I know that would work, I am trying to understand if there is a way to catch the error within the areThereErrors function rather that in the invoking of the test function.
No, there is not. Before areThereErrors is called, its parameters are evaluated, which in this case involves the call to the non-existent sumo, so execution stops before areThereErrors has a chance to be called. There is a reason try/catch is a language construct rather than a library call.
If sumo was a function that intentionally threw an error would areThereErrors be able to catch that?
@chasenyc Yes, it would because any error that occurs in the try is caught. No matter how deep. But, see my answer for reasons why try/catch should be used sparingly.
@torazaburo Thanks, I guess the crux of my issue was not understanding that parameters are evaluated before the function itself. Thanks for the prompt responses!
|
0

First, you should understand that not all errors are run-time errors that can be caught. A syntax error (like missing a bracket) will prevent the code from running in the first place.

Next, if you have code that may encounter run-time errors, you have two options:

  1. Use Try/Catch (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch for more)

    try{
        // some code to "try" to execute
    } catch (ex) {
        // programmatic flow is passed here if code in try causes exception
        // Actual exception object can be accessed through catch argument (ex in this case)
    
    } finally {
        // Regardless of whether the try code succeeded or not, the finally will always be executed.
    
    }
    

WARNING: This is often misused by developers as a way to catch errors that should not have come up in the first place, but do because the developer didn't write robust enough code. Also, be aware that exception objects have catch block scope, as such there are performance implications to using try/catch as well as it leading to poor code quality.

  1. Set up error event handler

The window object provides a "hook" into an error event. Since most events "bubble" up to the window object. An event handler for window's error event can provide a catch all type of routine. But, there is no standard for implementing this technique as of yet and different clients use different code:

    // AddEventListener will pass the error object to your callback:
    window.addEventListener("error", function (evt) {
      console.log("ERROR: " + evt.message);
      console.log("\tURL: " + evt.filename);
      console.log("\tLine: " + evt.lineno);
      console.log("\tColumn: " + evt.colno);
      // The error "may" still be presented to user
    }, false);

    // Chrome & Opera pass error details and the error object
    // (new standard) via .onerror
    window.onerror = function (message, file, line, col, error) {
      console.log("ERROR: " + message);
      console.log("\tURL: " + file);
      console.log("\tLine: " + line);
      console.log("\tColumn: " + col);
      console.log("\tObject: " + error);
      return true;  // Indicate that error has been handled
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.