https://github.com/duydang2311/attempt
Dead simple Go-like error handling for JS, TS.
https://github.com/duydang2311/attempt
attempt error-handling result-pattern try try-catch
Last synced: 3 months ago
JSON representation
Dead simple Go-like error handling for JS, TS.
- Host: GitHub
- URL: https://github.com/duydang2311/attempt
- Owner: duydang2311
- License: mit
- Created: 2025-06-21T08:22:39.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-08-16T14:04:10.000Z (8 months ago)
- Last Synced: 2025-08-16T15:25:32.685Z (8 months ago)
- Topics: attempt, error-handling, result-pattern, try, try-catch
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/@duydang2311/attempt
- Size: 18.6 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @duydang2311/attempt
[](https://bundlejs.com/?q=@duydang2311/attempt)
Functional error handling for JavaScript and TypeScript. Inspired by "Error as Value" in functional programming, `attempt` provides a clean, predictable way to manage operations that can succeed or fail.
## Installation
```bash
bun add @duydang2311/attempt
```
## Usage
```typescript
import { attempt } from '@duydang2311/attempt';
const divideUnsafe = (a: number, b: number) => {
if (b === 0) { throw new Error("Can't divide by zero!"); }
return a / b;
};
const divideSafe = (a: number, b: number) => {
if (b === 0) { return attempt.fail('ERR_DIVIDE_BY_ZERO'); }
return attempt.ok(a / b);
};
const resultUnsafe = divideUnsafe(10, 2); // number (might throw)
const resultSafe = attempt.sync(() => divideUnsafe(10, 2))(); // Attempt
// assuming divide by zero is the only exception that might happen
const resultSafeBetter = attempt.sync(() => divideUnsafe(10, 2))(e => 'ERR_DIVIDE_BY_ZERO'); // Attempt
const resultSafeEvenBetter = divideSafe(10, 2); // Attempt
// do some operations the functional way
const output = resultSafeEvenBetter.pipe(
attempt.map(a => `Success: ${a}`),
attempt.unwrapOrElse(e => `Error: ${e}`)
); // string
console.log(output);
```
## License
MIT License. See [LICENSE](LICENSE) for details.