語境
我想在我的網站后端執行命令列呼叫。如果這個命令列呼叫失敗,我想捕獲錯誤并拋出一個新的自定義錯誤。
我試圖拋出錯誤如下:
async function someFunction(): Promise<void> {
...
const result = exec(`some command`);
result.on('error', (error) => {
console.log(error.message);
throw error;
});
}
和
async function someFunction(): Promise<void> {
...
exec(`some command`, (error) => {
if (error) {
throw error;
}
});
}
并像這樣抓住它:
try {
await someFunction();
} catch (e) {
...
throw new Error('Meaningfull error')
}
問題
但是代碼永遠不會到達 catch 塊,因為它在我遇到 throw 錯誤的那一刻就關閉了。
Error: Command failed: some Command: Kommando nicht gefunden. //(Command not found)
at ChildProcess.exithandler (node:child_process:398:12)
at ChildProcess.emit (node:events:527:28)
at ChildProcess.emit (node:domain:475:12)
at maybeClose (node:internal/child_process:1092:16)
at Socket.<anonymous> (node:internal/child_process:451:11)
at Socket.emit (node:events:527:28)
at Socket.emit (node:domain:475:12)
at Pipe.<anonymous> (node:net:709:12) {
code: 127,
killed: false,
signal: null,
cmd: 'some Command'
}
Waiting for the debugger to disconnect...
[nodemon] app crashed - waiting for file changes before starting...
我嘗試洗掉錯誤處理嘗試,并且該應用程式繼續關注自己的業務。我不明白為什么當我嘗試處理錯誤時它總是崩潰......
我知道,命令失敗,我不在乎。我只想能夠處理錯誤。
編輯 1
我還嘗試了在 exec 呼叫周圍的 try catch。
try {
exec(`some Command`, (error) => {
if (error) {
throw error;
}
});
} catch (e) {
throw e;
}
但遺憾的是,該應用程式在拋出錯誤行處崩潰。
編輯 2
我使用基于 restify 中間件的錯誤處理程式
this.restify.on('uncaughtException', function(req, res, route, err) {
res.send(500, err.message);
});
舉個例子。以下代碼正在按預期處理:
if (!newUser.course) {
console.log('no course selected');
throw new Error('signal/no-course'); // error is thrown and handled accordingly
}
try {
await someFunction(newUser); // error in someFunction is thrown and crashes the app...
} catch (e) {
console.log(e);
throw new Error('signal/add-user');
}
我還嘗試在每個捕獲中添加 console.log(error) 。沒有幫助。
uj5u.com熱心網友回復:
您好,我認為解決此問題的正確方法是將其包裝到 Promise 中,因為它是回呼中的錯誤,如果您真的想嘗試捕獲發生的錯誤,則必須在回呼中完成據我所知。
可能的解決方案:
function someFunction() {
return new Promise((resolve, reject) => {
exec(`some command`, (error) => {
if (error) {
reject(error);
}
resolve("coding is fun ??");
});
})
}
async function main() {
try {
await someFunction();
} catch (e) {
console.error(e)
throw e;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/486091.html
標籤:javascript 节点.js 打字稿 执行 重新调整
上一篇:從json獲取值時保持陣列順序
