这是我的代码示例。我想在if/else
块中使用现有的try-catch
语句,并在验证失败时推送。我正在尝试在try-catch
之间使用if/else
,这给我一个错误。
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);
}
答案 0 :(得分:0)
您的Block尚未关闭。
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 :(得分:0)
您可以抛出一个新错误以直接转到catch
,例如:
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);
}
演示:
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);
答案 2 :(得分:0)
像这样更新您的代码
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);
}