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

erroz

v1.1.0

Published

Create abstract errors with meta-data, stack-traces and speaking error-messages

Downloads

1,265

Readme

erroz

Descriptive errors through metadata

Build Status

Typical strategies of parsing errors are fragile and couple code to the error messages. By defining error objects consistently, working with errors becomes predictable and efficient.

Features

  • arbitrary error metadata
  • templated error messages
  • stack traces
  • JSend format errors

Example

var erroz = require("erroz");

var DuplicateError = erroz({
    name: "Duplicate",
    code: "duplicate",
    statusCode: 409,
    template: "Resource %resource (%id) already exists"
});

// ...

throw new DuplicateError({ resource: "Unicorn", id: 1 });

/*
 throw new DuplicateError();
 ^
 Duplicate: Resource Unicorn (1) already exists
 at Object.<anonymous> (/erroz/examples/staticErrorMessage.js:14:7)
 at Module._compile (module.js:456:26)
 at Object.Module._extensions..js (module.js:474:10)
 at Module.load (module.js:356:32)
 at Function.Module._load (module.js:312:12)
 at Function.Module.runMain (module.js:497:10)
 at startup (node.js:119:16)
 at node.js:902:3
 */

Installation

npm install --save erroz

Defining errors

var errorDefinition = {
    name: "NotFound",
    template: "%resource (%id) not found"
};

var NotFoundError = erroz(errorDefinition);

errorDefinition object

Arbitrary data structure for metadata which will be available on every error instance. Some attributes have a special meaning which is why they are described below:

name string

The name displayed when the error is thrown.

message string

A static error message.

template string

A dynamic error message. Variable substitution from the data object is done with %<variable name>.

Throwing (with data object)

var data = { resource: "Unicorn", id: 1 };
throw new NotFoundError(data);
// Duplicate: Resource Unicorn (1) already exists

data object

A set of data to be used with the errorDefinition.template property.

Throwing (with error message)

var overrideMessage = "You are not authorized to eat my cookies";
throw new ForbiddenError(overrideMessage);
// Forbidden: You are not authorized to eat my cookies

overrideMessage string

A message to override errorDefinition.message or errorDefinition.template. Use of this option will set error.data to an empty object.

JSON

Errors can be converted to JSON with JSON.stringify().

var err = new DuplicateError({ resource: "Unicorn", id: 1 });
console.log(JSON.stringify(err));

/*
 {
    "name": "Duplicate",
    "code": "duplicate",
    "status": "fail",
    "statusCode": 409,
    "template": "Resource %resource (%id) already exists",
    "data": {
        "resource": "Unicorn",
        "id": 1
    },
    "message": "Resource Unicorn (1) already exists"
 }
 */

Custom JSON format

The AbstractError.toJSON method can be defined to customize the JSON format.

// Set a custom `toJSON` method for all errors
erroz.AbstractError.prototype.toJSON = function() {
    return {
        name: this.name,
        code: this.code
    };
};

console.log(JSON.stringify(err));
/*
 {
    "name": "Duplicate",
    "code": "duplicate"
 }
 */

error.toJSend()

Converts the error to a JSend-style object.

var err = new DuplicateError({ resource: "Unicorn", id: 1 });

err.toJSend();

/*
 {
    "status": "fail",
    "code": "duplicate",
    "message": "Resource Unicorn (1) already exists",
    "data": {
    	"resource": "Unicorn",
    	"id": 1,
    	"stack": "Duplicate: Resource Unicorn (1) already exists\n    at Object.<anonymous> (/erroz/examples/				  toJson.js:13:11)\n    at Module._compile (module.js:				  456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load 				  (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at 			     Function.Module.runMain (module.js:497:10)\n    at startup (node.js:119:16)\n    at node.js:				  906:3"
    	}
}
*/

Options

renderMessage function

Define a custom error renderer.

erroz.options.renderMessage = function(data, template) {
    return "Ooops";
}

includeStack boolean

Whether the stack should be included in errors. Default is true.

erroz.options.includeStack = false;

Consider turning this off in production and sending it to a logger instead.

Pro Tip: Using erroz with Connect / Express error handlers

Define a global error handler which calls toJSend() if the error is an instance of erroz.AbstractError. why do this? So you can simply next all your errors in your route-handlers.

function myAwesomeRoute(req, res, next) {
    if (!req.awesome) {
        next(new NotAwesomeError()); 
        return; 
    }

    next();
}	
app.use(function errozHandler(err, req, res, next) {
    if (err instanceof errorz.AbstractError) {
        res.status(err.statusCode).send(err.toJSend()); 
        return; 
    } 

    // Pass on all non-erroz errors
    next(err);
});

Licence

MIT