WiringPi / WiringPi-Node

Node.js bindings to wiringPi
333 stars 94 forks source link

[Proposal] Throw "System Error" exceptions instead of returning ints #59

Open NoHomey opened 7 years ago

NoHomey commented 7 years ago

I would like to propose to switch from C style errors to node's exceptions. Node did so with libuv very long time ago. I can't even find the first commit with change from returning -1 to throwing exception ... Now augmented Errors are thrown all over node's source code: https://github.com/nodejs/node/blob/95ba482a8ee663a1333ccc52b372e81d39df7166/lib/util.js#L1021, https://github.com/nodejs/node/blob/db1087c9757c31a82c50a1eba368d8cba95b57d0/deps/npm/lib/utils/spawn.js#L33, https://github.com/nodejs/node/blob/7bc6aeac86e6ce09efba4b04190b7792fc72fded/lib/dns.js#L17 alot more can be found reading node's source.

System Errors are as well documented in the API Documentation.

Such change is needed for a lot of reasons but mainly because JavasSript, node, v8 and respectively C++ are not C. In C the only way to indicate that some function failed is to return anything other than 0 (there are historical reasons why 0 aka EXIT_SUCCESS means that no errors occurred during a function execution, most of which are related to how CPUs treats numbers, what negative numbers means to the kernel and how is this than delegate to the user ...) But in JavasSript, node, v8 and C++ there are exceptions and they exist because they can provide more information about what failed, give more descriptive human readable error message and also change control flow.

WiringPi is written in C and dose inherit the return code error mechanism but wiring-pi is written in C++ and is meant to act as glue between WiringPi and JavaScript which uses exceptions and not errno and so it must inherit from the JavaScript native error mechanism ...

So I want all functions that return -1 to indicate error to throw augmented Error instead. Which will as well save the user from redundant checking of errno which is not even exposed in node (only POSIX errno codes are, under global.os.constatns.errno) since is not meant to be checked from user JavaScript code ...

For example all functions that return opened file descriptor should throw Error with code and errno set to returned errno code name ('EACCES' for an example) and syscal to 'open'. Other examples could be serialDataAvail to only return the number of characters available for reading, or to throw for any error condition.

If this proposal get approved these is the task list than needs to be done:

I would also like to do all of the above and all other that is needed to move wirng-pi from returning -1 to throwing exceptions.