1

Assuming the following code:

   let test = dbCall();
    console.log(test);

Now I want to wrap the dbcall in a try catch. Which way is better:

let test = null;
try{
    test = dbCall();
} catch(e) {
    console.log(e);
}
console.log(test);


try{
    var test = dbCall();
} catch(e) {
    console.log(e);
}
console.log(test);
3
  • 1
    How about a combination of the two: put the console.log(test) inside the try body? Commented May 1, 2017 at 13:40
  • @DarinDimitrov the console.log is just there for demonstration purposes. There is actually other code that needs to be outside the try block Commented May 1, 2017 at 13:49
  • I know this, my point was that this code could very well be put inside a function and then inside the try body simply replace the console.log statement with a call to this function by passing it the test value as parameter. Commented May 1, 2017 at 13:51

2 Answers 2

1

If you want handle return and throw a custom error:

var test = dbCall();

try { 
    if(test == <dbCall_error_state>) throw "Custom error here.";
}
catch(e) {
    alert("Error: " + e);
}

PS You need replace 'dbCall_error_state' with the return error of dbCall.

If you want throw direcly the error returned by dbCall(), conforming to the ECMAScript specification:

try {
    dbCall(); // may throw three types of exceptions
} catch (e) {
    if (e instanceof TypeError) {
        // statements to handle TypeError exceptions
    } else if (e instanceof RangeError) {
        // statements to handle RangeError exceptions
    } else if (e instanceof EvalError) {
        // statements to handle EvalError exceptions
    } else {
       // statements to handle any unspecified exceptions
       logMyErrors(e); // pass exception object to error handler
       alert("Error: " + e); // or alert it
    }
}

You can see detailed info about this here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/try...catch

Sign up to request clarification or add additional context in comments.

Comments

0

The first option is the more proper way to do this. Since the second option could leave you with test is not defined. I'd also make sure the code never reaches your 'example code' or the test logging in case an error was caught (so have a return or exit statement inside your catch block).

function makeDbCall() {
  let test = null;

  try{
    test = dbCall();
  } catch(e) {
    console.log(e);
    return false;
  }

  // only a successful DB call makes it this far
  console.log(test);
  return true;
}

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.