A lightweight JavaScript utility for clean error handling with optional AI-style runtime suggestions, without repetitive try/catch blocks.
npm install safe-try-with-aiconst { safeTry } = require("safe-try-with-ai");
const [err, result] = safeTry(() => JSON.parse('{"x":1}'));
if (err) {
console.error(err);
} else {
console.log(result); // { x: 1 }
}const { safeTryAsync } = require("safe-try-with-ai");
const [err, data] = await safeTryAsync(async () => {
return await fetchData();
});
if (err) {
console.error(err);
}Enable AI-style runtime suggestions by passing { analyze: true } as the second argument.
const { safeTry } = require("safe-try-with-ai");
const [err] = safeTry(() => JSON.parse("invalid"), { analyze: true });
if (err) {
console.error("Error:", err.message);
console.log("Suggestion:", err.suggestion);
console.log("Fix:", err.fix);
}AI-style suggestions are rule-based and local. No real AI model, no network calls, no data collection.
Use safeTryDefault to return a fallback value when an error occurs.
const { safeTryDefault } = require("safe-try-with-ai");
const result = safeTryDefault(
() => JSON.parse("invalid"),
{},
{ analyze: true }
);
console.log(result); // {}const { safeTryJson } = require("safe-try-with-ai");
const [err, data] = safeTryJson('{"x":1}', { analyze: true });
if (err) {
console.error(err);
}Validate JSON files from the terminal:
npx safe-try-with-ai example.json
npx safe-try-with-ai example.json --analyzecat example.json | npx safe-try-with-ai --stdin
cat bad.json | npx safe-try-with-ai --stdin --analyzeValidate JSON from pipes:
cat file.json | safe-try-with-ai --stdin -a- ✔ JSON valid (green)
- ✖ JSON invalid (red)
- Suggestions (blue)
- Fix (green)
0= valid JSON1= invalid JSON or runtime error
Built-in TypeScript definitions included:
import { safeTry } from "safe-try-with-ai";
const [err, result] = safeTry(() => JSON.parse(data));No configuration required.
- Works with synchronous and asynchronous functions
- Eliminates repetitive try/catch blocks
- Optional AI-style runtime suggestions
- Default fallback handling
- Safe JSON parsing helper
- CLI support via
npxand--stdin - Built-in TypeScript definitions
- Zero dependencies
- Lightweight and fast
- Fixed CLI execution issues
- Added short
-aflag - Improved stdin handling
- Reduced npm package size
- Added
--stdinsupport for piping JSON to CLI - CLI improvements for clearer output with colors and symbols
- Enhanced CLI with colors and symbols for valid/invalid JSON
- Improved AI-style suggestions formatting
- Bug fixes and small improvements
- Minor CLI fixes
- Added TypeScript definitions
- Added CLI support
- Documentation improvements
- Added
safeTryDefault - Added
safeTryJson - Improved AI-style suggestions
- Improved JSON error suggestions
MIT