Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active August 28, 2019 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daliborgogic/365c2ad3999872ba10e8dcb1cac1a1a1 to your computer and use it in GitHub Desktop.
Save daliborgogic/365c2ad3999872ba10e8dcb1cac1a1a1 to your computer and use it in GitHub Desktop.
Split Business and Native errors Async/Await Node.js
const { parse } = require('url')
const fetch = require('node-fetch')
/*
Native Error types
@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
*/
const nativeExceptions = [
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
].filter(except => typeof except === 'function')
/*
Throw native errors
@link https://github.com/gunar/go-for-it/blob/master/src/index.js#L18
*/
function throwNative(error) {
for (const Exception of nativeExceptions) {
if (error instanceof Exception) throw error
}
}
// Helper for removing async/await try/catch
function oops(promise) {
return promise.then(data => {
if (data instanceof Error) {
throwNative(data)
return [data]
}
return [null, data]
}).catch(error => {
throwNative(error)
return [error]
})
}
async function user (id) {
return await (await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)).json()
}
async function getUserById (id) {
try {
const [error, data] = await oops(user(id))
if (error) {
// Business logic errors
console.log('Business logic error', error)
}
// Bail/retry if required data missing
if (!data) {
return 'NICE TRY'
}
return { data }
} catch (error) {
// Native errors
console.log('Native JS error: ', error)
}
}
module.exports = async (req, res) => {
const parsed = parse(req.url, true)
const { id } = parsed.query
try {
return await getUserById(id)
} catch (error) {
console.log('Final catch: ', error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment