throwif operator

Ron Buckton Ron.Buckton at
Wed Apr 12 00:10:17 UTC 2017

I’d much rather see something more like C# 7’s throw expressions:

// original example
fs.writeFile("message.txt", "Hello Node.js", err => err ? throw err : console.log("The file has been saved.");

// better example
function choose(kind) {
  return kind === 0 ? choseZero() : kind === 1 ? chooseOne() : throw new Error("out of range");


From: es-discuss [mailto:es-discuss-bounces at] On Behalf Of T.J. Crowder
Sent: Tuesday, April 11, 2017 5:20 AM
To: Elie Rotenberg <elie at>
Cc: Нурбек <nurbek.ab at>; es-discuss <es-discuss at>
Subject: Re: throwif operator

I don't think we need a new keyword for this, both because of Elie's point about handling it with a `throwif` function, and because Node's callback pattern is a bit old-fashioned in the world of promises and async/await. Until the Node API is updated to support promises natively, you can use one of the various "promisifying" libs to promisify the API:

const pfs = /*...promisified version of fs*/;

...and then:

pfs.writeFile("message.txt", "Hello Node.js")
    .then(() => console.log("The file has been saved."));

...and like your original code snippet, it will (on recent versions) terminate Node if you don't handle the error.

Combined with `async`/`await`, it becomes even cleaner:

await pfs.writeFile("message.txt", "Hello Node.js");
console.log("The file has been saved.");

(Of course, that has to be within an `async` function.)

-- T.J. Crowder

On Tue, Apr 11, 2017 at 1:15 PM, Elie Rotenberg <elie at<mailto:elie at>> wrote:
const throwIf = (fn) => (err, ...args) => {
  if(err) throw err;
  return fn(...args);


fs.writeFile('message.txt', 'Hello Node.js', throwIf(() => console.log('The file has been saved')));

No need to extend the language and preempt keywords with stuff you can very easily implement in userland.
I'm not even convinced such a construct would be a good idea anyway to encourage rethrowing errors without thinking if it can be handled locally.

On Tue, Apr 11, 2017 at 2:06 PM, Нурбек <nurbek.ab at<mailto:nurbek.ab at>> wrote:
An example from node.js documentation:

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('The file has been saved!');

This looks like a common way to handle errors when the first parameter is an instance of Error.

Yes, this line of code is short and easy to copy-paste.
But introducing something like this:

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  throwif err;
  console.log('The file has been saved!');

would make the code much cleaner and bring some sort of standart way to handle such errors.

es-discuss mailing list
es-discuss at<mailto:es-discuss at><>

es-discuss mailing list
es-discuss at<mailto:es-discuss at><>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list