Skip to content

Instantly share code, notes, and snippets.

@DonutEspresso
Created May 17, 2019 01:45
Show Gist options
  • Save DonutEspresso/85576b8c217909a6ef2d3918f18edb0e to your computer and use it in GitHub Desktop.
Save DonutEspresso/85576b8c217909a6ef2d3918f18edb0e to your computer and use it in GitHub Desktop.
Promise Error Model
'use strict';
const mockClient = {};
// The Promise model groups unintentional errors with errors into the same
// try/catch mechanism.
//
// In most typed languages this is fine because the catch clause gives you some
// flexibility to catch only the errors you are interested in. JS gives you a
// catch all, which makes it hard to distinguish the errors.
async function doStuff() {
let rand = Math.random();
let x;
if (rand > 0.7) {
// throws a TypeError
// imagine this leaks a socket underneath the hood.
// $ echo $? => ?
mockClient.call();
} else if (rand > 0.3) {
// return error to be handled
// $ echo $? => ?
throw new Error('handle me!');
}
// happy path
// $ echo $? => 0
return 'success';
}
(async function() {
try {
const msg = await doStuff();
console.log('completed!', msg);
} catch (e) {
// How do I tell which one is a ReferenceError and which one is my
// error? I only want to rethrow one of them. Becomes more difficult
// when you are 10 layers deep into an async function call.
throw e;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment