Last active
November 12, 2025 09:34
-
-
Save daliborgogic/365c2ad3999872ba10e8dcb1cac1a1a1 to your computer and use it in GitHub Desktop.
Split Business and Native errors Async/Await Node.js
This file contains hidden or 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
| import { parse } from 'node:url' | |
| /* | |
| 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) | |
| } | |
| } | |
| export default 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