0.1.1 • Published 5 years ago

dissect-error v0.1.1

Weekly downloads
1
License
ISC
Repository
github
Last release
5 years ago

Dissect Error

Build Status

Parse some js error and extract a sort of usefull info like:

  • type (SyntaxError, ReferenceError, etc)
  • message
  • error site
  • line
  • column
  • code that threw the error
  • file
  • stack trace (parsed as array)

Works with runtime errors, syntax errors, node VM eval errors and plain eval errors

And have zero dependencies!

How to use?

1. Install it

npm install -S dissect-error

2. Import it

const dissect = require( 'dissect-error' );

3. Use it

try {
  // throw some error
} catch ( err ) {
  const info = dissect( err );

  console.log( info );
}

Properties

The dissect function return an object with the following properties:

propertydescription
.typeJS error types like: Error, SyntaxError, MyCustomError, etc
.messageThe message from the error
.siteWhat threw the error, Eg. Object.eval
.lineLine # where the error happen
.columnColumn # where the error happen
.stackArray of frames from the stack trace, each frame is an object (see below)
.expressionExpression which threw the error. Eg: const 2 = 1;
.fileThe file which threw the error. Eg: /app/project/index.js

The .stack returns an array of stack frames wich have the folowing properties

propertydescription
.siteWhat thre the error. Eg. Object.eval
.fileThe file which threw the error
.lineLine # where the error happen
.columnColumn # where the error happen

Use cases

Plain runtime errors

try {
  await IO();
} catch ( err ) {
  const parsed = dissect( err );

  // result
  parsed.line; // 2
  parsed.expression; // await IO();
  parsed.site; // IO;
}

Node VM errors

Node VM errors are a bit different as they are parsed relative to the code evaluated by the VM, instead of the context of the VM invokation.

const vm = require( 'vm' );
const dissect = require( 'dissect-error' );

const code = `
module.exports = ( => };
`;

const ctx = { module, require, console, global, process };
vm.createContext( ctx );

try {
  vm.runInNewContext( code, ctx, { displayErrors: true } );
} catch ( err ) {
  const parsed = dissect( err );
  
  // result 
  parsed.type; // SyntaxError
  parsed.message; // Unexpected token =>
  parsed.line; // 2 (relative to the "code" parsed by the node VM)
  parsed.expression; // 'module.exports = ( => };
}