1

This is an example of my code. I want to use my existing if/else statement inside a try-catch block, and push when validation fails. I'm trying to use try-catch in between if/else condition and it gives me an error.

var errLogs = [];
try {
  var a = "ABCD";
  if(typeof a === "string"){
     console.log("equel");
  }catch(e) {
  }else{
     console.error("not equel");
  }
  console.log(e);
  errLogs.push(e);
}
1
  • You should close if block within try block. Commented Jul 10, 2018 at 3:52

3 Answers 3

7

You can throw a new error to go directly to catch like:

var errLogs = [];

try {
  var a = "ABCD";   // or, test it with number 123

  if (typeof a === "string") {
    console.log("equel");
  } else {
    throw new TypeError("not equel")
  }

} catch (e) {
  console.log(e);
  errLogs.push(e);
}

DEMO:

var errLogs = [];

function testString(value) {
  try {
    if (typeof value === "string") {
      console.log("equel");
    } else {
      throw new TypeError("not equel")
    }

  } catch (e) {
    console.log(e.message);
    errLogs.push(e.message);
  }
}


testString('ABCD');
console.log('Now testing with number --->')
testString(123);

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

Comments

-1

Update your code like this

var errLogs = [];

try {
  var a = "ABCD";
  if(typeof a === "string"){
    console.log("equel");
  }
  else{
    console.error("not equel");
    //you dont need else there- once exception is thrown, it goes into catch automatically
  }
}catch(e) {
        console.log(e);
        errLogs.push(e);
}

Comments

-2

Try somthing like this.

    function IsString(d){
      try {
        if(typeof d==='string'){
          return {isString:true,error:""}; 
        }
          return  {isString:false,error:`data type is ${typeof(d)}`}; 
        } catch (err) {
           return  {isString:false,error:`error:${e}`}; 
        }
    }
    
    //TEST CASE
    let errorLogs=[]
    
    //#1
    let check1=IsString(null);
    errorLogs.push(check1)
    
    //#3
    let check2=IsString(123);
    errorLogs.push(check2)
    
    //#4
    let check3=IsString('');
    errorLogs.push(check3)
    
    //#5
    let check4=IsString('');
    errorLogs.push(check4)
    
    //Output
    console.log(errorLogs)

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.