Node Events 2 – Error Handling

Node in Practice 第四章 – EventsEmitter – Error Handling。


“error”事件是 EventEmitter 中的特殊事件之一,在没有监听时,触发后会在终端打印 stacktrace 并终止进程。

采用 node 的 domain 模块可以很优雅的捕获 error event,避免 Node 陷入不可控状态。

参考:

  1. Alex Young, Marc Harter. Node in Practice. 2015
// Node in practice 4.2 Error handling

// 1. event-based errors
// Node doc:
// When an EventEmitter instance experiences an error, 
// the typical action is to emit an error event. Error 
// events are treated as a special case in Node. 
// If there is no listener for it, then the default action
// is to print a stack trace and exit the program.
;(function () {
  'use strict';

  ;const MusicPlayer = (function () {

    const util = require('util');
    const events = require('events');

    const $ = function () {
      events.EventEmitter.call(this);
    };

    util.inherits($, events.EventEmitter);

    return $;
  }());

  // The demo usage:
  const musicPlayer = new MusicPlayer();

  musicPlayer.on('play', function (track) {
    this.emit('error', 'unable to play!');
  });

  musicPlayer.on('error', function (error) {
    console.error(`Error: ${error}`);
  });

  setTimeout(() => {
    musicPlayer.emit('play', 'Little Comets - Jennifer');
  }, 1000);
}());


// 2. Managing errors with domain
;(function () {
  'use strict';

  const util = require('util');
  const events = require('events');
  const domain = require('domain');

  const audioDomain = domain.create();

  ;const AudioDevice = (function () {
    
    const self = { };
    const $ = function () {
      events.EventEmitter.call(this);

      self._play = (function () {
        this.emit('error', 'Not implemented yet');
      }).bind(this);

      this.on('play', self._play);
    };

    util.inherits($, events.EventEmitter);

    return $;
  }());

  ;const MusicPlayer = (function () {

    const self = { };
    const $ = function () {
      events.EventEmitter.call(this);

      self.audioDevice = new AudioDevice();
      self._play = (function () {
        self.audioDevice.emit('play');
        console.log('Now playing');
      }).bind(this);

      this.on('play', self._play);
      
      this.emit('error', 'No audio are available');
    };

    util.inherits($, events.EventEmitter);

    $.prototype.play = function () {
      self._play();
    };

    return $;
  }());

  // The demo usage:
  audioDomain.on('error', function (error) {
    console.log(`audioDomain error ${error}`);
  });

  audioDomain.run(() => {
    const musicPlayer = new MusicPlayer();
    musicPlayer.play();
  })
}());

作者: V

Web Dev

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s