Skip to content

Commit

Permalink
feat: guardedInvokeFn
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Aug 13, 2023
1 parent 83dd91a commit 6d109ec
Show file tree
Hide file tree
Showing 6 changed files with 1,042 additions and 1,281 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,22 @@ if (error)
console.error(error)
```

### Guarded Functions

With `guardedInvokeFn` you can create a function that can be called with the same arguments, but guarded. This is useful when you want to guard a function that you don't own, like `JSON.parse`:

```ts
import { guardedInvokeFn } from 'unres'

const safeJSONParse = guardedInvokeFn(JSON.parse)

let result = safeJSONParse('{ "test": 1 }')
console.log(result.data) // { test: 1 }

result = safeJSONParse('{ missing the other one')
console.log(result.error) // SyntaxError: Unexpected character 'm'
```

## Custom Error Handling

unres offers the flexibility to implement custom error handling strategies by overriding the default error type. This can be done by passing a custom error type as the second argument to the `guardedInvoke` function:
Expand Down
16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "unres",
"type": "module",
"version": "0.1.2",
"packageManager": "pnpm@8.5.1",
"packageManager": "pnpm@8.6.12",
"description": "Go-like error handling for try/catch blocks",
"author": "Johann Schopplich <pkg@johannschopplich.com>",
"license": "MIT",
Expand Down Expand Up @@ -38,12 +38,12 @@
"test:types": "tsc --noEmit"
},
"devDependencies": {
"@antfu/eslint-config": "^0.39.0",
"@types/node": "^18.16.13",
"bumpp": "^9.1.0",
"eslint": "^8.41.0",
"typescript": "^5.0.4",
"unbuild": "^1.2.1",
"vitest": "^0.31.1"
"@antfu/eslint-config": "^0.40.2",
"@types/node": "^20.4.10",
"bumpp": "^9.1.1",
"eslint": "^8.47.0",
"typescript": "^5.1.6",
"unbuild": "^2.0.0-rc.0",
"vitest": "^0.34.1"
}
}
Loading

0 comments on commit 6d109ec

Please sign in to comment.