Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mehdizonjy/safe-error
https://github.com/mehdizonjy/safe-error
Last synced: 9 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/mehdizonjy/safe-error
- Owner: MehdiZonjy
- Created: 2018-10-14T07:28:47.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T21:37:09.000Z (almost 2 years ago)
- Last Synced: 2024-10-05T11:34:58.476Z (about 1 month ago)
- Language: TypeScript
- Size: 300 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 12
-
Metadata Files:
- Readme: README.MD
Awesome Lists containing this project
README
# Safe Error
This module is inspired by how golang handles errors, and allows you catch errors in a similar manner## Example
```javascript
const {safe} = require('safe-error')
const safeJsonParse = (str) => safe( () => JSON.parse(str))const {result, error} = safeJsonParse('{"msg": "Hello World}')
if(error) {
console.log('Invalid Json')
}
else {
console.log(result)
}```
It can also handle promise functions```javascript
const axios = require('axios')
const {safeAsync} = require('safe-error')
const safeGET = (url) => safeAsync( () => axios.get(url))const main = async () => {
const {result, error} = await safeGET('http://invalidurl')
if(error) {
console.log('Failed to call endpoint', error)
}
else {
console.log(result.data)
}
}
main()```
## API
`type Result = {error: Error|null, result: T|null}``safe( () => T) => Result`
`safeAsync( () => Promise) => Promise`