使用Node.js child_process捕获致命错误

I'm relatively new to hardcore Node.js hacking so I'm seeing all sorts of lovely new errors that I have no clue how to solve when I initially see them.  To this point I've managed to keep a smile on my face while trying to fix these errors, a quality I quite enjoy about myself.  One of the recent errors I encountered was with child_process, whereby an error would occur within an execSync command and the entire app would brick; not even  a try/catch would save me.  I did find a solution, however.

我对Node.js硬核入侵比较陌生,因此我看到各种各样可爱的新错误,当我初次看到这些错误时,我不知道如何解决。 到目前为止,在设法解决这些错误时,我一直保持笑容,这是我非常享受的一种品质。 我遇到的最近错误之一是child_process ,它在execSync命令中发生错误,整个应用程序变砖; 即使try/catch也无法拯救我。 我确实找到了解决方案。

JavaScript (The JavaScript)

The best way to catch errors without letting your app brick is by using the process' spawn (or in this case spawnSync) method:

捕获错误而不让您的应用程序积木的最佳方法是使用进程的spawn (或在本例中为spawnSync )方法:


var childProcess = require('child_process');

var commitMessage = (function() {
	var spawn = childProcess.spawnSync('git', ['log', '--format=%B', '-n', '1']);
	var errorText = spawn.stderr.toString().trim();

	if (errorText) {
	  console.log('Fatal error from `git log`.  You must have one commit before deploying.');
	  throw new Error(errorText);
	}
	else {
	  return spawn.stdout.toString().trim();
	}
})();


With this method you can check the stderr buffer first; if there's a String from it you know it errored out, if no error text then the process was clean!

使用这种方法,您可以首先检查stderr缓冲区; 如果有一个字符串,您就知道它出错了,如果没有错误文本,则说明过程很干净!

翻译自: https://davidwalsh.name/catching-fatal-errors-nodejs-childprocess

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值