Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including saferr with all npm packages installed. Try it out:

var saferr = require("saferr")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

saferr v1.0.1

A tiny JavaScript library for safe error-handling. Supports async/await, promises and regular functions. Inspired by Go.

Description

A zero-dependency JavaScript library for error handling. It is inspired by Go, and returns a tuple containing the error and the result instead of throwing an exception.

Unlike other JavaScript libraries (await-to-js), supports async/await, promises and regular functions.

Installation

npm i saferr

Examples

Async

import saferr from "saferr";
import axios from "axios";

const safeGet = saferr(axios.get);

const testAsync = async url => {
  const [err, result] = await safeGet(url);

  if (err) {
    console.error(err.message);
    return;
  }

  console.log(result.data.results[0].email);
};


// prints: zdenka.dieckmann@example.com
testAsync("https://randomuser.me/api/?results=1");

// prints: Network Error
testAsync("https://shmoogle.com");

Sync

import saferr from "saferr";

const syncFunc = shouldThrow => {
  if (shouldThrow) {
    throw new Error("Oops...");
  }

  return "ok";
};

const safeSyncFunc = saferr(syncFunc);

const testSync = ({succeed}) => {
  const [err, result] = safeSyncFunc(succeed);

  if (err) {
     console.error(err.message);
     return;
  }

  console.log(result);
};

// prints: ok
testSync({succeed: true});

// prints: Oops...
testSync({succeed: false});
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free