Last active
February 17, 2023 17:16
-
-
Save maxgfr/c375cfaa107de89b1a33f97a464248a3 to your computer and use it in GitHub Desktop.
Typescript error handling : https://twitter.com/housecor/status/1612222617141878784
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
export async function createUser() { | |
const {user, error} = await api.createUser(); | |
if(error) { | |
throw new UserError({ | |
name: "CREATE_USER_ERROR", | |
message: "Failed to create user", | |
cause: error | |
}) | |
} | |
} |
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
export class ErrorBase<T extends string> extends Error { | |
name: T; | |
message: string; | |
cause: any; | |
constructor(error: ErrorWithCause<T>) { | |
super(); | |
this.name = error.name; | |
this.message = error.message; | |
this.cause = error.cause; | |
} | |
} | |
interface ErrorWithCause<T> { | |
name: T; | |
message: string; | |
cause: any; | |
} | |
class UserError extends ErrorBase<"GET_USER_ERROR" | "CREATE_USER_ERROR"> {} |
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
try { | |
await createUser(); | |
} | |
catch(e) { | |
if(e instanceof UserError && e.name === "CREATE_USER_ERROR") { | |
toast(e.message) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment