基于node.js中的错误代码处理错误

时间:2015-05-22 11:25:20

标签: javascript node.js error-handling

我在node.js中创建了一个命令行应用程序,它严重依赖于节点的文件系统模块(读取,更新,创建新文件等)。我为了同样的目的写了很多函数。

现在我的问题是:'我可以全局捕捉由于任何功能而发生的错误吗?'

例如:

func1();  // throws some error: Cannot find file , errCode:xyz
func2();  // throws some error: Cannot find file , errCode:xyz

//some global error catcher    
func(catch errCode:xyz){
          console.log("Cannot find file. Make sure file exist and path is correct.");
    }

SS

1 个答案:

答案 0 :(得分:2)

您可以收听https://nodejs.org/api/process.html#process_event_uncaughtexception

File "coding.ch17.py", line 55, in <module>
ch17()
File "coding.ch17.py", line 48, in ch17
result = solve_ch17(fn)
File "coding.ch17.py", line 35, in solve_ch17
result = check_output(['ocrad', fn + '.ppm']).strip().replace(' ', '')
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

但是不建议这样做,因此您可能不应该让应用程序继续运行,因为它可能处于未知状态。

你的函数应该首先执行带有错误的回调,node-style,并且传递回调的函数应该以正确的方式处理错误。