Skip to content

Instantly share code, notes, and snippets.

@markusait
Created May 20, 2020 03:05
Show Gist options
  • Save markusait/aeb04fdb50611eebd2a7304b2c2b7b7f to your computer and use it in GitHub Desktop.
Save markusait/aeb04fdb50611eebd2a7304b2c2b7b7f to your computer and use it in GitHub Desktop.
Approach to do error handling in typescript
// Usually one wowuld import these declerations like such
// import { ok, err, Result } from './util'
export declare type Result<T, E>
= Ok<T, E> // contains a success value of type T
| Err<T, E> // contains a failure value of type E
// utility functions to build Ok and Err instances
export declare const ok: <T, E>(value: T) => Ok<T, E>
export declare const err: <T, E>(err: E) => Err<T, E>
export declare class Ok<T, E> {
readonly value: T
constructor(value: T)
isOk(): this is Ok<T, E>
isErr(): this is Err<T, E>
}
export declare class Err<T, E> {
readonly error: E
constructor(error: E)
isOk(): this is Ok<T, E>
isErr(): this is Err<T, E>
}
// What is being returned from the API
type ResponseData = {
statusCode: number
responseBody?: Object
addData: Object
success: boolean
}
const api = {
get: (url: string): ResponseData => {
return { success: true, statusCode: 200, responseBody: { url: url }, addData: null }
}
}
// This function could be located in API or APIReact
const bottomFunc = async (url: string): Promise<Result<ResponseData, Error>> => {
try {
const resp = await api.get(url)
//responsibility of Developer to check what should be regarded an error and what not
if (!resp.success || resp !== null) {
return err(new Error(
'Invalid string passed into `makeHttpRequest`. Expected a valid URL.'
))
}
resp.addData = { 'user': '0xx' }
return ok(resp)
} catch (e) {
switch (e) {
// case 'AlreadySentException':
// return ok('Already sent')
default:
return err(new Error(
'unexpected Error' + e
))
}
}
}
// This function could be located in API or APIReact
const middleFunc = async (url: string): Promise<Result<ResponseData, Error>> => {
const result = await bottomFunc(url)
return result
}
// This function could be located in Web
const topFunc = async () => {
// we have a Result<ResponseData, Error>
const result = await middleFunc('https://myUrl.doc')
if (result.isOk()) {
// do something with the success value like redirect
console.log(result.value)
} else {
// do something with the failure value like display error on Form
console.error(result.error)
}
}
topFunc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment