簡體   English   中英

ES6模塊中的process.on('uncaughtException')處理

[英]process.on('uncaughtException') handling in ES6 modules

我在ES6模塊中有一個奇怪的行為:

index.mjs

process.on('uncaughtException', err => {
  console.log('Oh no!');
  process.exit(1);
});

import mod from './module.mjs';

module.mjs

export default 'foo';
throw new Error('I am broken');

我希望在運行babel-node index.mjsnode --experimental-modules index.mjs時執行uncaughtException處理程序,但事實並非如此。 返回:

throw new Error('I am broken');
^

Error: I am broken
    at Object.<anonymous> (mod.mjs:2:7)
    ...

使用良好的舊CommonJS模塊,它可以工作:

index.js

process.on('uncaughtException', err => {
  console.log('Oh no!');
  process.exit(1);
});

const mod = require('./module.js');

module.js

module.exports = 'foo';
throw new Error('I am broken');

node index.js返回:

Oh no!

這使我感到困惑。 這是設計使然嗎?如果是這樣,那么uncaughtException處理程序如何與ES6模塊一起使用? 任何想法表示贊賞!

在運行模塊中的任何代碼之前,將靜態解析ES6導入,並加載(並執行)依賴項。 使用CommonJS模塊,只有在您調用require時才發生這種情況。

如果某個模塊壞了以致於加載它會引發異常,則任何依賴於該模塊的模塊都不會運行。 這幾乎是設計使然。

但是,您可以使用動態導入並處理以下錯誤:

// index.mjs:
import('./module.mjs').then(mod => {
   …
}, err => {
  console.log('Oh no!');
  process.exit(1);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM