[ES7] Handle Errors in Asynchronous Functions

This lesson shows how regular control flow statements such as try/catch blocks can be used to properly handle errors in asynchronous functions. Oftentimes, the resulting code is easier to read than complex promise chains with .catch()methods.

const fetch = require('node-fetch');
const BASE_URL = 'https://api.github.com/users';

class GithubUser {
    async fetchGitHubUser(handle) {
        const response = await fetch(`${BASE_URL}/${handle}`);
        const body =  await response.json();

        if (response.status !== 200) {
            throw Error(body.message);
        }

        return body;
    }
}

(async () => {
    const github = new GithubUser();

    try {
        const user = await github.fetchGitHubUser('zhentian-wan');
        console.log(user);
    } catch(err) {
        console.error(err);
    }


})();

 

posted @ 2017-05-04 04:42  Zhentiw  阅读(158)  评论(0)    收藏  举报