未加星标

JavaScript: Handling errors like Go

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

Back in August, I wrote an article in Brazilian-Portuguese explaining how I use async / await to isolate error handling.

Today I'll translate it to English but with different examples!

I love how Go handle side-effects in a synchronous-like manner. Let's see this example from the net/http package:

func main() { res, err := http.Get("http://example.com/") if err != nil { // handle `err` } // do something with `res` }

Or perhaps the os package:

func main() { file, err := os.Open("words.txt") if err != nil { // handle `err` } // do something with `file` }

Implementation details aside, I was wondering if there's a way to write something like this in javascript?

Well, as they say, where there's a will, there's a way! :joy:

Everyday Promise-like functions

Nowadays Promise-like environments are common amongst us.

We can use it to read a file in Node.js:

let util = require("util"); let fs = require("fs"); let read = util.promisify(fs.readFile); function main() { read("./test.js", { encoding: "utf8" }) .then(file => { // do something with `file` }) .catch(err => { // handle `err` }); } main();

Perhaps fetching some data from an API:

let url = "https://dog.ceo/api/breeds/image/random"; function main() { fetch(url) .then(res => res.json()) .then(res => { // do something with `res` }) .catch(err => { // handle `err` }); } main();

And being lazy by nature, we create functions to hide some boilerplate for us, so we can write less code across the codebase:

let readFile = require("./readFile"); function main() { readFile("./test.js") .then(file => { // do something with `file` }) .catch(err => { // handle `err` }); } main(); // readFile.js let util = require("util"); let fs = require("fs"); let read = util.promisify(fs.readFile); module.exports = path => { return read(path, { encoding: "utf8" }) .then(file => { return file; }) .catch(err => { throw err; }); };

And:

let api = require("./api"); function main() { api.getRandomDog() .then(res => { // do something with `res` }) .catch(err => { // handle `err` }); } main(); // api.js let url = "https://dog.ceo/api/breeds/image/random"; let api = {}; api.getRandomDog = () => { return fetch(url) .then(res => res.json()) .catch(err => { throw err; }); }; module.exports = api;

Still, there's a lot of repetition here, there's .then and .catch in both sides of this code snippet.

They say async / await can fix this, so...let's try it then?

Converting to async / await

Let's see how our Node.js is doing in async / await :

let readFile = require("./readFile"); async function main() { try { let res = await readFile("./test.js"); // do something with `file` } catch (err) { // handle `err` } } main(); // readFile.js let util = require("util"); let fs = require("fs"); let read = util.promisify(fs.readFile); module.exports = async path => { try { let res = await read(path, { encoding: "utf8" }); return res; } catch (err) { throw err; } };

And how can we fetch our dog with it:

let api = require("./api"); async function main() { try { let res = await api.getRandomDog(); // do something with `res` } catch (err) { // handle `err` } } main(); // api.js let url = "https://dog.ceo/api/breeds/image/random"; let api = {}; api.getRandomDog = async () => { try { let res = await fetch(url); let json = await res.json(); return json; } catch (err) { throw err; } }; module.exports = api;

Phew... I think we changed a problem by another. Now there's try...catch in both places. Thinking about our current interface between consumer/service, we've:

In our main() function we're calling a "service" ( readFile and api. ) Our "service" function returns a Promise When fulfilled, our service returns a payload When rejected, our service throw an error

Hmm... perhaps this is the problem! Our interface between consumer/service are different for fulfilled and rejected scenarios.

Refreshing our memory about our Go example at the top:

func main() { res, err := http.Get("http://example.com/") if err != nil { // handle `err` } // do something with `res` }

Seems we've the same interface for both, fulfilled and rejected scenario!

Let's try that with our last async / await example!

Unified return interface with async / await

In our Node.js example:

let readFile = require("./readFile"); async function main() { let [err, file] = await readFile("./test.js"); if (err) { // handle `err` } // do something with `file` } main(); // readFile.js let util = require("util"); let fs = require("fs"); let read = util.promisify(fs.readFile); module.exports = async path => { try { let res = await read(path, { encoding: "utf8" }); return [null, res]; } catch (err) { return [err, null] } };

And our Fetch API:

let api = require("./api"); async function main() { let [err, res] = await api.getRandomDog(); if (err) { // handle `err` } // do something with `res` } main(); // api.js let url = "https://dog.ceo/api/breeds/image/random"; let api = {}; api.getRandomDog = async () => { try { let res = await fetch(url); let json = await res.json(); return [null, json]; } catch (err) { return [err, null] } }; module.exports = api;

Well done!! :tada::tada::tada:

That's exactly what we were looking for! Our main() function looks like our Go example and now we've isolated all try...catch in our "service" functions.

Using this approach you can clean up your Node.js Middlewares/Controllers and in your Front-end, let's say with React/Redux, clean up redux-thunks or redux-sagas functions/generators.

You can also unit test these "service" functions in isolation and guarantee they are returning the expected interface/data.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:JavaScript: Handling errors like Go
本站链接:https://www.codesec.net/view/611090.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(76)