Might Fail
A TypeScript library for handling async and sync errors without try
and catch
blocks. Inspired by other languages that utilize Result
or Either
types for safer error handling.
This works for sync and async code, and you can choose the error handling style that you like.
Other languages
Install
import { mightFail } from "might-fail"
const [networkError, result] = await mightFail(fetch("/posts"))
if (networkError) {
// handle network error
return
}
if (!result.ok) {
// handle an error response from server
return
}
const [convertToJSONError, posts] = await mightFail(
result.json()
)
if (convertToJSONError) {
// handle convertToJSONError
return
}
posts.map((post) => console.log(post.title))
import { mightFail } from "might-fail"
const [networkError, result] = await mightFail(fetch("/posts"))
if (networkError) {
// handle network error
return
}
if (!result.ok) {
// handle an error response from server
return
}
const [convertToJSONError, posts] = await mightFail(
result.json()
)
if (convertToJSONError) {
// handle convertToJSONError
return
}
posts.map((post) => console.log(post.title))
import { mightFail } from "might-fail"
const [networkError, result] = await mightFail(fetch("/posts"))
if (networkError) {
// handle network error
return
}
if (!result.ok) {
// handle an error response from server
return
}
const [convertToJSONError, posts] = await mightFail(
result.json()
)
if (convertToJSONError) {
// handle convertToJSONError
return
}
posts.map((post) => console.log(post.title))
import { mightFail } from "might-fail"
const [networkError, result] = await mightFail(fetch("/posts"))
if (networkError) {
// handle network error
return
}
if (!result.ok) {
// handle an error response from server
return
}
const [convertToJSONError, posts] = await mightFail(
result.json()
)
if (convertToJSONError) {
// handle convertToJSONError
return
}
posts.map((post) => console.log(post.title))