DEV Community

Discussion on: JavaScript: Handling errors like Go

Collapse
 
oieduardorabelo profile image
Eduardo Rabelo

how are you rhymes? thanks for your comment!

JS wasn't designed to have a Go style of exceptions

not discussing the way the language handles side-effects (golang is built-in and javascript you need to wrap it in something like shown in this article), my personal experience is: it's just a matter of interface response pattern

i've being using it for node.js, typescript, flowtype, you name it... and it works pretty well, is just another pattern inside your codebase

in your example the error you pass on could be generated by .fetch() or by .json() and it's not going to be clear inside the main function

there is nothing preventing you to massage these responses... you can easily branch it in the catch:

api.getRandomDog = async () => {
  try {
    let res = await fetch(url);
    let json = await res.json();
    return [null, json];
  } catch (err) {
    if (err === "fetch-error") {
      return ["fetch-error", null]
    }
    if (err === "json-error") {
      return ["json-error", null]
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

in the same way you can inspect the error in the main function:

async function main() {
  let [err, res] = await api.getRandomDog();

  if (err === "fetch-error") {
    // handle fetch error
  }

  if (err === "json-error") {
    // handle json error
  }

  // do something with `res`
}
Enter fullscreen mode Exit fullscreen mode

use your imagination, but be consistent! :) ... is rare when we need to have these granular error handling in the front-end... in my perspective, your back-end should be handling it (checking for missing params, not found user, credentials, etc)...

in an node.js/express world, your error middleware would be responsible for these branches and the client response/rejection could be only one!

many thanks 👋

Collapse
 
rhymes profile image
rhymes • Edited

how are you rhymes? thanks for your comment!

well thanks :D hope the same for you

i've being using it for node.js, typescript, flowtype, you name it... and it works pretty well, is just another pattern inside your codebase

Sure, I'm not against it, it's just that in a way you're limited to your perimeter of code, I wouldn't use it in a third party library. Most JS developers expect failure to be escalated to an exception so that if it's synchronous it can be caught and if it's async it can be handled. If suddenly you start returning two-valued arrays you're changing a silent contract. See how complicated it's going to be to change the way Go error handling is done. And Go is nowhere near as popular as JS.

It's not a bad idea inside an app though, as you say, if it's used consistently.

Thank you for your perspective!