使用node.js创建缓冲区期间捕获错误

时间:2016-02-01 08:48:16

标签: javascript node.js error-handling try-catch buffer

假设我使用带有以下代码的node.js创建二进制缓冲区;

SELECT 
   [ID],
   [ID2],
   [name],
   [class],
   (iif(not isnull([example]), Replace([example], "~", nz((select top 1 [name] from Data T2 where T2.ID2 = T1.ID2 and T2.[class]="main" order by T2.[ID2]),"")),null)) as [ExampleNew]
FROM Data T1

这会产生这样的错误;

  

buffer.js:568           return this.hexWrite(string,offset,length);                       ^

     

TypeError:十六进制字符串无效       在TypeError(本机)       在Buffer.write(buffer.js:568:21)       at fromString(buffer.js:115:26)       在新的缓冲区(buffer.js:54:12)

如何修改代码以捕获此错误而不是突然退出?

1 个答案:

答案 0 :(得分:1)

可以简单地使用try / catch块,因为它是同步的。

msg_str = "0105A"; //this gives error. Correct version will be something like "0105AB"
try {
  buffer_binary = new Buffer(msg_str, "hex"); // specify hex
} 
catch (err){
  // return, callback or whatever else you want to happen
}    
console.log(msg_str); 
console.log(buffer_binary);