Created
July 10, 2020 07:03
-
-
Save neharkarvishal/f3a68e9426a4eb7ef1c74dcb99cc7026 to your computer and use it in GitHub Desktop.
Typescipt error handling
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
/* Return tuple types, with a nullable error component just like Go */ | |
/* meta: Typescript 3.9.5 */ | |
type Err = Error | null; | |
async function getUser(): Promise<[string, Err]> { | |
try { | |
const res = await fetch('/me'); | |
const data = await res.json(); | |
return [data, null]; | |
} catch (err) { | |
return ['', err]; | |
} | |
} | |
(async () => { | |
const [user, err] = await getUser(); | |
if (err !== null) { | |
console.error(err); | |
return; | |
} | |
console.log(user); | |
})(); |
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
/* Return Result/Option types just like Rust */ | |
/* meta: Typescript 3.9.5 */ | |
type Result<T> = ({ success: true } & T) | { success: false; err: Error }; | |
async function getUser(): Promise<Result<{ user: string }>> { | |
try { | |
const res = await fetch('/me'); | |
const user = (await res.json()) as string; | |
return { success: true, user }; | |
} catch (err) { | |
return { success: false, err }; | |
} | |
} | |
(async () => { | |
const result = await getUser(); | |
if (!result.success) { | |
console.error(result.err); | |
return; | |
} | |
console.log(result.user); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment