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

@ryanmorr/blunder

v0.1.1

Published

A modern client-side JavaScript error handler

Downloads

4

Readme

blunder

Version Badge License Build Status

A modern client-side JavaScript error handler

Install

Download the CJS, ESM, UMD versions or install via NPM:

npm install @ryanmorr/blunder

Usage

Blunder offers the ability to enhance, dispatch, capture, and report JavaScript errors in the browser:

import { monitor, subscribe, dispatch, report } from '@ryanmorr/blunder';

// Listen for global runtime errors
monitor();

// Subscribe to be notified when an error is dispatched
subscribe((error) => {
    // Send the error to the server
    report('/path/to/error/logger', error).then((response) => {
        // Error was successfully logged to the server
    });
});

// Manually dispatch an error
dispatch('An error occurred!');

API

Exception(message?, detail?)

Exception is a subclass of the Error class for creating errors with enhanced capabilities, including metadata, custom details, a formatted stacktrace, and easy serialization to JSON:

import { Exception } from '@ryanmorr/blunder';

// Create an exception with an error message and an object of custom details
const ex = new Exception('error', {
    sourceModule: 'foo',
    sourceFunction: foo
});

// Standard properties
ex.name;
ex.message;
ex.stack;

// Metadata
ex.meta.datetime; // The date and time as a string
ex.meta.timestamp; // The time in milliseconds since the UNIX epoch
ex.meta.userAgent; // The user agent string
ex.meta.url; // The URL of the current page that generated the exception
ex.meta.referrer; // The URL of the page that linked to the current page
ex.meta.cookie; // The unformatted cookie string or "disabled" if cookies are disabled
ex.meta.language; // The default language of the user's browser
ex.meta.readyState; // The loading state of the current page (loading/interactive/complete)
ex.meta.viewportWidth; // The viewport width of the browser window in pixels
ex.meta.viewportHeight; // The viewport height of the browser window in pixels
ex.meta.orientation; // The orientation (landscape/portrait) of the user's device
ex.meta.connection; // The type of the user's connection (slow-2g/2g/3g/4g)
ex.meta.memory; // MB of the memory heap used
ex.meta.memoryPercent; // Percent of the allocated memory heap used

// Custom details
ex.detail.sourceModule; //=> "foo"
ex.detail.sourceFunction; //=> foo

// Formatted stacktrace
ex.stacktrace.forEach(({functionName, fileName, lineNumber, columnNumber}) => {
    console.log(`${functionName} in ${fileName}:${lineNumber}:${columnNumber}`);
});

// Includes a `toJSON` method for serialization
const json = JSON.stringify(ex);

Extend Exception to create your own custom error subclasses:

class CustomException extends Exception {}

Exception also has a static from method that can be used to convert a value into an Exception instance:

// Supports error messages as strings
const ex = Exception.from('error');

// Supports normal error instances (will copy message and stack properties)
const error = new Error();
const ex = Exception.from(error);

// Supports creating instances of subclasses
const ex = CustomException.from('error');
ex instanceof CustomException; //=> true

dispatch(error, detail?)

Manually dispatch an Exception to the error subscribers and return the Exception instance:

import { dispatch } from '@ryanmorr/blunder';

// Supports strings
const ex = dispatch('error');

// Supports normal error instances
dispatch(new Error());

// Supports custom details as an optional second argument
dispatch('error', {foo: 1, bar: 2});

subscribe(callback)

Subscribe a callback function to be invoked with an Exception instance when an error is dispatched, it returns an unsubscribe function:

import { subscribe } from '@ryanmorr/blunder';

const unsubscribe = subscribe((ex) => {
    // An error was dispatched
});

monitor(config?)

Enable global error monitoring by listening for the error, unhandledrejection, and rejectionhandled events. To customize which events to listen for, provide an object with the event name as the key and a boolean as the value to indicate inclusion of the event. It returns a function to disable monitoring:

import { monitor } from '@ryanmorr/blunder';

// Listen for all error events by default
const stop = monitor();

// Optionally specify which events to listen for
monitor({
    error: true,
    unhandledrejection: true,
    rejectionhandled: false
});

report(url, data)

Send errors to the server and return a promise that is fulfilled with the JSON response from the server and rejected with an Exception instance:

import { report } from '@ryanmorr/blunder';

const ex = new Exception();

// Send an error to the server
report('/path/to/error/logger', ex).then((response) => {
    // Error successfully logged to server
});

stacktrace(error?)

Generate a formatted stacktrace:

import { stacktrace } from '@ryanmorr/blunder';

// Get a stacktrace from the invocation point
const trace = stacktrace();

// Get a stacktrace from an error instance
const trace = stacktrace(error);

// Get a stacktrace from a stack string
const trace = stacktrace(error.stack);

attempt(fn)

A simple wrapper for a try/catch block that returns a promise. The promise is fulfilled with the return value of the function argument if it executed without throwing an error. The promise is rejected with an Exception instance when an error is thrown which is automatically dispatched to the error subscribers:

import { attempt } from '@ryanmorr/blunder';

attempt(() => {
    // Try something and return a value
}).then((val) => {
    // Execution was successful
}).catch((ex) => {
    // Execution failed
});

License

This project is dedicated to the public domain as described by the Unlicense.