TimLuo465 / baidu-translate-api

A free and unlimited API for Baidu Translate
MIT License
71 stars 17 forks source link

Error handling #18

Closed jonaslund closed 4 years ago

jonaslund commented 4 years ago

How to do proper error handling?

Running it with no Internet, which may happen in various installations, should happen cleanly and with proper error reporting, currently it results in a unhandled promise rejection,

    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
(node:63019) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing
 inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To 
terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see
 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

Thanks

jonaslund commented 4 years ago

Solution. Put a catch error block in the request() function, like so

    request() {
        const { from, requestOpts } = this.opts;

        return new Promise(resolve => {
            if (from !== Auto) {
                resolve()
            } else {
                this.langdetect().then(lan => {
                    this.opts.from = lan;
                    resolve();
                });
            }
        }).then(() => {
            return cookie.get(requestOpts).then(() => this.trans());
        }).catch((err) => {
            return "error";
        }); 
    }