npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jsonify-error

v2.0.0

Published

Convert errors to JSON or to a good string. Develop faster with better error messages.

Downloads

7,710

Readme

jsonify-error

npm package

NPM version Build status Minzipped size License NPM downloads Dependency Status Dev Dependency Status Open Issues Closed Issues contributions welcome jsDelivr hits

Convert errors to JSON or to a good string. Develop faster with better error messages.

It's 2019 and still the default behavior of JavaScript could be better with regard to displaying/manipulating errors:

  • JSON.stringify(e): Bad
  • e.toString(): Bad
  • e.toJSON(): Doesn't exist
  • console.log(e): Bad in browsers, not so bad in Node but could be better

But jsonify-error comes to the rescue:

  • For JSON.stringify(e):
    • Use JSON.stringify(jsonifyError(e)) instead
    • Or call jsonifyError.overrideErrorMethods() once and then JSON.stringify(e) will work.
  • For e.toString():
    • Use jsonifyError.asString(e) instead
    • Or call jsonifyError.overrideErrorMethods() once and then e.toString() will work.
  • For e.toJSON():
    • Use jsonifyError(e) instead
    • Or call jsonifyError.overrideErrorMethods() once and then e.toJSON() will work.
  • For console.log(e):
    • Use jsonifyError.log(e) instead
    • Or call jsonifyError.overrideConsole() once and then console.log(e) will work.

Installation

In Browsers

For browsers, simply include one of the dists in your entry point, such as dist/jsonify-error.js. The dists are available in jsDelivr:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jsonify-error.min.js" integrity="sha384-k3Is8aV5PW6XO2NtZyFbjgZLKNWv4kFrtuN0cnOhaw+qKurzZIlOZZNmih+HGKpN" crossorigin="anonymous"></script>

The following dists are available (with source maps):

  • dist/jsonify-error.js
  • dist/jsonify-error.min.js
  • dist/jsonify-error.es5.js
  • dist/jsonify-error.es5.min.js

Or if you're developing a browser library with Browserify, you can just require it normally, as if you were in a Node environment.

In Node

In node, as usual, simply do:

npm install --save jsonify-error

Purpose

The main purpose of jsonify-error, as the name suggests, is to convert an error to a plain object. Just do jsonifyError(e) and you will get something like:

{
    "name": "TypeError",
    "className": "TypeError",
    "message": "It can't be a string",
    "superclasses": ["Error", "Object"],
    "enumerableFields": {
        // If the error has other fields they appear here (including in the prototype chain):
        "someField": "someValue"
    },
    "stack": [
        "TypeError: It can't be a string", 
        "at z (E:\\test.js:15:15)", 
        "at E:\\test.js:10:9", 
        "at Array.forEach (native)", 
        "at y (E:\\test.js:9:13)", 
        "at x (E:\\test.js:5:5)", 
        "at w (E:\\test.js:24:9)", 
        "at Object.<anonymous> (E:\\test.js:32:1)", 
        "at Module._compile (module.js:570:32)", 
        "at Object.Module._extensions..js (module.js:579:10)", 
        "at Module.load (module.js:487:32)"
    ]
}

If you're thinking "Great! Now I can do console.log(jsonifyError(e)) instead of console.log(e)" in a browser, you're in the right track, but you can do even better! A few utility methods are exposed by jsonifyError beyond the main one, as mentioned in the beginning of this README.

  • jsonifyError.log(e): Logs the error in a much better way than console.log(e).
  • jsonifyError.overrideConsole(): Makes console.log, console.warn, console.error work like jsonifyError.log automatically. Calling this once is enough.
  • jsonifyError.overrideErrorMethods(): Heavily improves e.toString() and adds e.toJSON() to all errors automatically. Calling this once is enough.

Example: with try-catch blocks

const jsonifyError = require("jsonify-error");

try {
    // ...
} catch (e) {
    jsonifyError.log(e);
    // ...
}

Example: with promises

const jsonifyError = require("jsonify-error");

somethingAsync().then(() => {
    // ...
}).catch(error => {
    jsonifyError.log(e);
    // ...
});

Also, for promises, there is a sibling module called better-promise-error-log which takes care of showing the improved logs automatically for unhandled rejections.

Example: with express

var jsonifyError = require("jsonify-error");

app.get('/your/api', (req, res) => {
    // ...
    // Instead of res.status(500).json(error), do:
    res.status(500).json(jsonifyError(error));
});

Note: if you've overriden error methods (by calling jsonifyError.overrideErrorMethods()), the above can be simplified to res.status(500).json(error) (see the overriding methods section).

Example usage: overriding methods

const jsonifyError = require("jsonify-error");
jsonifyError.overrideConsole();
jsonifyError.overrideErrorMethods();
// Now `console.log`, `console.warn` and `console.error` will be much better.
// Also, `e.toString()` will be much better and `e.toJSON()` will be available.

Contributing

Any contribution is very welcome. Feel free to open an issue about anything: questions, suggestions, feature requests, bugs, improvements, mistakes, whatever. I will be always looking.

Changelog

The changelog is available in CHANGELOG.md.

See also

License

MIT (c) Pedro Augusto de Paula Barbosa