Last active
February 28, 2020 02:00
-
-
Save superj80820/c0e2cc96921e99f6c0e34638a03d6ad1 to your computer and use it in GitHub Desktop.
Handle js async error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function requestAPI() { //requestDB 實作都類似只是reject的error不同 | |
return new Promise((resolve, reject) => { | |
request('https://A.com', (error, data) => { | |
if (error) reject(new customError("I'am requestAPI",error)) | |
else resolve(data) | |
}) | |
}) | |
} | |
// main | |
try { | |
await requestAPI() | |
await requestDB() | |
} catch (error) { | |
switch (error.name) { | |
case "I'am requestAPI": | |
console.log('requestAPI error') | |
break | |
case "I'am requestDB": | |
console.log('requestDB error') | |
break | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function requestAPI() { //requestDB 實作都類似只是reject的error不同 | |
return new Promise((resolve, reject) => { | |
request('https://A.com', (error, data) => { | |
if (error) resolve(error) | |
else resolve(data) | |
}) | |
}) | |
} | |
// main | |
responseAPI = await requestAPI().catch(error => error) | |
if (_.isError(responseAPI)) { | |
console.log('requestAPI error') | |
} | |
responseDB = await requestDB().catch(error => error) | |
if (_.isError(responseDB)) { | |
console.log('requestDB error') | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function requestAPI() { //requestDB 實作都類似只是reject的error不同 | |
return new Promise((resolve, reject) => { | |
request('https://A.com', (error, data) => { | |
if (error) resolve([null, error]) | |
else resolve([data, null]) | |
}) | |
}) | |
} | |
// main | |
[responseAPI, errorAPI] = await requestAPI() | |
if (errorAPI) { | |
console.log('requestAPI error') | |
} | |
[responseDB, errorDB] = await requestDB() | |
if (errorDB) { | |
console.log('requestDB error') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment