fivdi / i2c-bus

I2C serial bus access with Node.js
MIT License
348 stars 57 forks source link

Refactor Error objects #12

Closed fivdi closed 9 years ago

fivdi commented 9 years ago

Currently Error objects generated by i2c-bus only contain a message property. This can result in code that needs to examine the message strings in order to determine what to do. Code like this:

      scanBus.receiveByte(addr, function (err) {
        if (err) {
          if (err.message !== 'Remote I/O error' &&
              err.message !== 'Input/output error' &&
              err.message !== 'Device or resource busy') {
            return cb(err);
          }
        } else {
          addresses.push(addr);
        }

        next(addr + 1);
      });

and this:

    try {
      scanBus.receiveByteSync(addr);
      addresses.push(addr);
    } catch (e) {
      if (e.message !== 'Remote I/O error' &&
          e.message !== 'Input/output error' &&
          e.message !== 'Device or resource busy') {
        throw e;
      }
    }

Error objects should contain message, errno, code, and syscall properties in order to make it possible to write code like this:

      scanBus.receiveByte(addr, function (err) {
        if (err) {
          if (err.errno !== EIO &&
              err.errno !== EREMOTEIO &&
              err.errno !== EBUSY) {
            return cb(err);
          }
        } else {
          addresses.push(addr);
        }

        next(addr + 1);
      });

and this:

    try {
      scanBus.receiveByteSync(addr);
      addresses.push(addr);
    } catch (e) {
      if (e.errno !== EIO &&
          e.errno !== EREMOTEIO &&
          e.errno !== EBUSY) {
        throw e;
      }
    }
fivdi commented 9 years ago

This will be a breaking change as Nan::ErrnoException will be used for creating Error objects. The message property of Error objects created by Nan::ErrnoException are prefixed with the appropriate code. For example, the message "Input/output error" will become "EIO, Input/output error".

fivdi commented 9 years ago

Implemented with https://github.com/fivdi/i2c-bus/commit/718f6f62e76c706143de05aae48b74a81022616a and published in v1.0.0.