Skip to content

Instantly share code, notes, and snippets.

@ThomasKruegl
Created March 27, 2018 14:32
Show Gist options
  • Save ThomasKruegl/c4167df3201705e2c53e75f31ccf9030 to your computer and use it in GitHub Desktop.
Save ThomasKruegl/c4167df3201705e2c53e75f31ccf9030 to your computer and use it in GitHub Desktop.
class MyError extends Error {
}
async function doSomething() {
return Promise.resolve({value: 5});
}
async function doSomethingElse(value: number): Promise<string> {
return Promise.reject(new Error("myMessage"));
}
// several try/catch blocks, requiring let declarations
async function separateTries() {
let first: number;
try {
first = (await doSomething()).value;
} catch (error) {
throw new MyError(error.message + "internalStuff");
}
if (first > 10) {
throw new MyError("internal check failed" + "internalStuff");
}
let second: string;
try {
second = await doSomethingElse(first);
} catch (error) {
throw new MyError(error.message + "internalStuff");
}
// do something with second
const result = second + "!!!111elf"
return result;
}
// one try/catch block. requires specific handling of intermediate check
async function oneTry() {
try {
const first = (await doSomething()).value;
if (first > 10) {
// i can return a rejected Promise directly
return Promise.reject(new MyError("internal check failed" + "internalStuff"));
// i can throw an error so the local catch handles it correctly
// throw new MyError("internal check failed");
}
const second = await doSomethingElse(first);
// do something with second
const result = second + "!!!111elf"
return result;
} catch (error) {
throw new MyError(error.message + "internalStuff");
}
}
// mix async/await and promise chaining
async function mixWithChaining() {
function helper(error: Error): never {
throw new MyError(error.message + "internalStuff");
}
const first = (await doSomething().catch(helper)).value;
if (first > 10) {
throw new MyError("internal check failed" + "internalStuff");
}
const second = await doSomethingElse(first).catch(helper);
// do something with second
const result = second + "!!!111elf"
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment