fivdi / i2c-bus

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

Throwing error in asynchronous functions #65

Closed captain1991cv closed 5 years ago

captain1991cv commented 5 years ago

Hi @fivdi

I'm using your library in my code, im gonna illustrate my problem in a short code, when i run the fallowing code, im expecting to see console.log("errorOnServer", err); on the screen:

const i2c = require('i2c-bus');
var CurrentI2CBus = i2c.openSync(1);
var myBuffer = Buffer.alloc(2);
CurrentI2CBus.i2cRead(0xff, 0x2, myBuffer, function (err, bytesRead, returnBuffer) {
    if (err) {
        console.log("errorOnServer", err);
        return;
    }
})

But, what I'm getting is this:

pi@raspberrypi:~/Desktop/myNodejsFiles $ node server.js
/home/pi/Desktop/myNodejsFiles/node_modules/i2c-bus/i2c-bus.js:62
    throw new Error('Invalid I2C address ' + addr);
    ^

Error: Invalid I2C address 255
    at checkAddress (/home/pi/Desktop/myNodejsFiles/node_modules/i2c-bus/i2c-bus.js:62:11)
    at Bus.i2cRead (/home/pi/Desktop/myNodejsFiles/node_modules/i2c-bus/i2c-bus.js:519:5)
    at Object.<anonymous> (/home/pi/Desktop/myNodejsFiles/server.js:20:15)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
    at internal/main/run_main_module.js:21:11
pi@raspberrypi:~/Desktop/myNodejsFiles $

I'm receiving my Address directly from the user. How can I handle this ?

fivdi commented 5 years ago

It's a fairly long post, but the way i2c-bus categorizes and handles errors is described here.

In the code posted above, 0xff is passed to i2cRead as the I2C device address. 0xff is not a valid I2C address. A valid I2C address is a integer >= 0 and <= 0x7f. Passing anything that is not a valid I2C address to i2cRead is regarded as a programming error or bug and results in an error being thrown. Note that throwing an error is the correct way for the asynchronous i2cRead method to handle the programming error.

The programming error or bug in this case is that the program forgot to validate the user input of 0xff. If the program is modified to validate the user input it can avoid passing the invalid address to i2cRead and the error will not be thrown.