Skip to content

Instantly share code, notes, and snippets.

@agazso
Last active November 20, 2020 16:20
Show Gist options
  • Save agazso/30389e5fab99db0c6b6cbda11ed03350 to your computer and use it in GitHub Desktop.
Save agazso/30389e5fab99db0c6b6cbda11ed03350 to your computer and use it in GitHub Desktop.
Type safe error handling in Typescript with classes
// compile: tsc error.ts --lib ES2015,dom
type Result<T> = T | Error
const isError = <T>(r: Result<T>): r is Error => (r instanceof Error)
class CustomError extends Error {
value: any
constructor(value, ...params) {
super(...params)
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error['captureStackTrace']) {
Error['captureStackTrace'](this, CustomError)
}
this.name = 'CustomError'
this.value = value
}
}
function toError(e: any) {
if (e instanceof Error) {
return e
} else if (typeof e === 'string') {
return new Error(e)
} else {
return new CustomError(e)
}
}
class Bee {
private constructor(readonly url: string) {
if (!url.startsWith('http://')) {
throw `invalid url: ${url}`
}
}
public static create(url: string): Result<Bee> {
try {
return new Bee(url)
} catch (e) {
return toError(e)
}
}
public static async asyncCreate(url: string): Promise<Result<Bee>> {
try {
return new Bee(url)
} catch (e) {
return toError(e)
}
}
}
async function main(): Promise<Result<void>> {
const url = 'http://localhost:8080/'
// const url = 'htts://localhost:8080/'
const bee = Bee.create(url)
if (isError(bee)) {
console.error(bee.message)
return bee
}
console.debug(bee.url)
const asyncBee = await Bee.asyncCreate(url)
if (isError(asyncBee)) {
console.error(asyncBee.message)
return asyncBee
}
console.debug(asyncBee.url)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment