
Check out the source code and don’t forget to drop a star EZ Clap
catchThis
Lightweight and pure javascript library that returns normalized errors as values instead of throwing them
Heavily inspired by @t3dotgg’s preferred way of handling try/catch in typescript and this comment peepoLove with some added normalization, because
throw undefinedis a thing
Install
Install using a package manager
pnpm i catch-this or using CDN
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.min.js"></script> Usage
The catchThis class has 3 static methods, auto, sync and async. For most cases, use auto it detects if the function being executed is async or a sync function
Sync
Using with sync functions
import { catchThis } from 'catch-this'
let { data, error } = catchThis.auto(() => {
//...
return 'my result'
})
console.log(error) // undefined
console.log(data) // my result Async
Using it with async functions a.k.a Promise
import { catchThis } from 'catch-this'
let { data, error } = await catchThis.auto(new Promise((resolve) => {
resolve('my promise result')
}))
console.log(error) // undefined
console.log(data) // my promise result Error normalization
All errors are normalized to a Error object MDN Reference
import { catchThis } from 'catch-this'
let { data, error } = await catchThis.auto(new Promise((_, reject) => {
reject('promise was rejected')
}))
console.log(error instanceof Error) // true
console.log(error.message) // promise was rejected NOTE: If the error is not a
object,stringorError, the error will be normalized with the messageno error message
| function | description |
|---|---|
auto() | Works with both sync and async function, if it is an async function, it needs await just like a normal promise |
sync() | Works only with callbacks or sync functions |
async() | Works only with promises of async functions |