JSPM

elegant-expression

0.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2
  • Score
    100M100P100Q12772F
  • License ISC

Library provides try/catch/finally as expression

Package Exports

  • elegant-expression
  • elegant-expression/dist/src/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (elegant-expression) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Elegant Expression

Actions Status Coverage

Library provides try/catch/finally as expression.

Install

npm i elegant-expression -S

Try/Catch/Finally

JavaScript and TypeScript (accordingly) provide the try/catch/finally only as statement.

When using a block of try/catch/finally creating different scopes and you will need to declare ahead the variables that are used within blocks. Additional, you should manual set types for this variables (you can't using smart detection types of variables) and make casting of error type in block of catch.

All this leads to the writing of boilerplate code and makes it difficult to read:

// Before 😮‍💨
let status: 'ok' | 'fail';
try {
  await fn();
  status = 'ok';
// error has type unknown
} catch (err: unknown) {
  const error = err as Error;
  status = 'fail';
}

// After 🙆‍♂️
import exp from 'elegant-expression';

// We get result of executing immediately in one place
const status = await exp
  .try(async () => {
    await fn();
    return 'ok';
  })
  // error already has type Error
  .catch((err: Error) => {
    console.error(err);
    return 'fail';
  });

try/catch/finally:

const result = await exp
  .try(async () => {
    await fn();
    return 'ok';
  }).catch((err) =>
    'fail'
  ).finally(() =>
    console.log('finally');
  );

try/finally:

const result = await exp
  .try(async () => {
    await fn();
    return 'ok';
  }).finally(() =>
    console.log('finally');
  );