ajel is a set of thin wrappers for try-catch, coupled with eslint rules to make a Typescript Result Type.
yarn add ajel eslint-plugin-ajel
pnpm add ajel eslint-plugin-ajel
// Handling async functions that throw
import { ajel } from 'ajel';
async function main() {
const result = await ajel(Promise.resolve('hello world'));
// Accessing result before narrowing union type throws eslint error
// console.log(result);
if (result instanceof Error) {
// This return narrows the type of result to its Result
return;
}
return result;
}
// Handling syncronous functions that throw
import { sjel } from 'ajel';
async function main() {
const result = sjel(JSON.parse, "{}");
// Accessing result before narrowing union type throws eslint error
// console.log(result);
if (result instanceof Error) {
// This return narrows the type of result to its Result
return;
}
return result;
}
ajel
and sjel
are thin wrappers for try-catch, coupled with eslint rules to encourage better error handling.
The linting tools are available in the package eslint-plugin-ajel
{
plugins: ['ajel'],
extends: [
'plugin:ajel/recommended',
],
}
import { ajel, sjel } from 'ajel';
class CustomError extends Error { }
class CustomError2 extends Error { }
class CustomError3 extends Error { }
const foobarFn = async () => {
const result = await ajel(Promise.resolve('result'));
const result2 = sjel(JSON.parse, '{}');
const result3 = await ajel(Promise.resolve('result'));
const result5 = sjel((stringvar: string) => stringvar, '{}');
//------ Test2 SJEL
if (result2 instanceof CustomError) {
//We can access the error here in BinaryExpression with var instanceof
console.log(result2);
return;
}
// Cant Access the result2 variable here
// console.log(result2);
if (result2 instanceof Error) {
console.log(result2);
// This return narrows the type of result2 to its Result
return;
}
// Type is narrowed - no longer a union of Result | Error -> just Result
console.log(result2);
//------ Test AJEL
// Cant Access the result variable here
// console.log(result);
switch (true) {
case result instanceof CustomError3:
//We can access the error here in BinaryExpression with var instanceof
console.log(test);
break;
//We support fall through
case result instanceof CustomError2:
case result instanceof CustomError:
console.log(result);
break;
case result instanceof Error:
break;
}
console.log(result);
//---- No handling of AJEL and SJEL returns reports Errors
// console.log(result3);
// console.log(result5);
};
docs
: A placeholder documentation site powered by Next.jsajel
: The core library (function)eslint-plugin-ajel
: Eslint rules for proper usage and error handling paradigmbenchmarks
: Testing ajel's performance against other methods