loading words...

Feb 06, 2019 09:08:10

async await catch

by @swizecteller | 368 words | 🐣 | 116💌

Swizec Teller

Current day streak: 0🐣
Total posts: 116💌
Total words: 32303 (129 pages 📄)

One thing that really bugs me about async/await is error handling.

Yes try catch is great, it might even make your code easier to read. Combined with JavaScript's modern block scoping it gives rise to the vile side of exception handling.

check this out 👇

---

Say you're using httpie to scream at a server as @peterpme would say.

You write something like this 👇

```

const { data } = await post("https://naughty.server", {

  body: {

     say: "Hello"

  }

})

```

---

Great. A post request to a naughty server. But the naughty server says no.

What do you do? Add a try catch. Wanna handle those JavaScript errors and show a message to the user.

```

try {

const { data } = await post("https://naughty.server", {

body: {

say: "Hello"

}

})

}catch(e) {

  console.error("Naughty server said no")

}

```

---

You're talking to a naughty server and handling errors like you're supposed to. 👏

What about not errors? You can take the data and do something.

```

try {

const { data } = await post("https://naughty.server", {

body: {

say: "Hello"

}

})

console.log(data.undefinedStuff.string)

}catch(e) {

console.error("Naughty server said no")

}

```

---

Oh no what just happened!? 😱

You're getting a "Naughty server said no" error even though _you_ made the mistake. You can't just access properties on undefinedStuff. JavaScript doesn't like that.

---

Oh I know! We can move playing with that data to after the catch block, right? That should work.

```

try {

const { data } = await post("https://naughty.server", {

body: {

say: "Hello"

}

})

}catch(e) {

console.error("Naughty server said no")

}

console.log(data.undefinedStuff.string)

```

---

Nope. Now data isn't defined because `const { data }` only works within that try block.

Ugh 🤦‍♂️

What else can we try?

---

This works I guess. But pre-declaring your variables like it's 1978? No thanks

```

let data;

try {

 data = await post("https://naughty.server", {

body: {

say: "Hello"

}

})

}catch(e) {

console.error("Naughty server said no")

}

console.log(data.undefinedStuff.string)

```

---

Ok what about this? Yeah that's never gonna get out of hand ...

```

try {

const { data } = await post("https://naughty.server", {

body: {

say: "Hello"

}

})

try {

console.log(data.undefinedStuff.string)

}catch(e) {

console.error("Data handling messed up")

}

}catch(e) {

console.error("Naughty server said no")

}

```

---

I'm gonna be honest with you: There's no solution. Not a nice one. Not in JavaScript.

Other languages let you catch specific error types. As far as I know, JavaScript doesn't (can't?) support that :/

Originally published at twitter.com

contact: email - twitter / Terms / Privacy