如何添加例外或以下节点功能管理错误?
这是我原来的代码:
function extract_number(conv){
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}
然而,它与字符串下降并不包含一些在这里提取例如:
extract_number('my number is')
我试图捕获错误如下:
function extract_number(err,conv){
if (err) {
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.error('There was an error', err);
}
console.log(value)
return value
}
我有:
/home/adolfo/node_js/index.js:61 const的结果= conv.match(正则表达式)^
TypeError: Cannot read property 'match' of undefined
at extract_number (/home/adolfo/node_js/index.js:61:29)
at Object.<anonymous> (/home/adolfo/node_js/index.js:69:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
在第二个功能,所以我想欣赏这个支持
回答如下:在try..catch是你的朋友
function extract_number(conv){
try{
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}catch(){
return null
}
}
如何添加例外或以下节点功能管理错误?
这是我原来的代码:
function extract_number(conv){
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}
然而,它与字符串下降并不包含一些在这里提取例如:
extract_number('my number is')
我试图捕获错误如下:
function extract_number(err,conv){
if (err) {
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.error('There was an error', err);
}
console.log(value)
return value
}
我有:
/home/adolfo/node_js/index.js:61 const的结果= conv.match(正则表达式)^
TypeError: Cannot read property 'match' of undefined
at extract_number (/home/adolfo/node_js/index.js:61:29)
at Object.<anonymous> (/home/adolfo/node_js/index.js:69:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
在第二个功能,所以我想欣赏这个支持
回答如下:在try..catch是你的朋友
function extract_number(conv){
try{
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}catch(){
return null
}
}