Skip to content

Instantly share code, notes, and snippets.

@thegecko
Created August 20, 2020 16:17
Show Gist options
  • Save thegecko/cc5f4df69cbef933eece666c58c46224 to your computer and use it in GitHub Desktop.
Save thegecko/cc5f4df69cbef933eece666c58c46224 to your computer and use it in GitHub Desktop.
Throwing a custom error in a TypeScript promise
export class RddiError extends Error {
constructor(public status: number) {
super();
}
}
export class TestHarness {
public async errorFunction(): Promise<void> {
throw new RddiError(12);
}
public async runAsync(): Promise<void> {
try {
await this.errorFunction();
} catch(error) {
if (error instanceof RddiError) {
console.log(error.status);
} else {
console.log("unknown error thrown!");
}
}
}
public runPromise(): Promise<void> {
return this.errorFunction()
.then(() => console.log("won't happen"))
.catch(error => {
if (error instanceof RddiError) {
console.log(error.status);
} else {
console.log("unknown error thrown!");
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment