DEV Community

Cover image for Explicit error messages with VError
Sacha Clerc-Renaud
Sacha Clerc-Renaud

Posted on

Explicit error messages with VError

Today I will present you one of my favorite NPM modules. VError makes your errors more explicit.

I will not expose all the features here and just explain why I think this module is very useful. So don't hesitate to read the official documentation here

The thing I like with VError is the feature of building a composite error message through all applicative layers the error goes through.

Let see an example :

const VError = require('verror')

function model(json) {
  return JSON.parse(json)
}

function controller(json) {
  try {
    model(json)
  } catch (err) {
    const error = new VError(err, 'Model fail to parse json')
    throw error
  }
}

function routeHandler(rawJSON) {
  try {
    const data = controller(rawJSON)
    return data
  } catch (err) {
    const error = new VError(err, 'Controller fail to use json')
    throw error
  }
}

routeHandler('invalid json')
Enter fullscreen mode Exit fullscreen mode

This script will generate the following error message :
VError: Controller fail to use json: Model fail to parse json: Unexpected token i in JSON at position 0

This is much more explicit to see than : SyntaxError: Unexpected token i in JSON at position 0

Also you can add some contextual information for each VError layers and get them at the end with the VError.info() function see documentation here

Examples :

const error = new VError({
  name: 'SERVICE_UNAVAILABLE',
  info: { json: rawJSON },
  cause: err,
}, 'Controller fail to use json')

console.log(VError.info(error)) // { json: 'invalid json' }
console.log(error.name) // SERVICE_UNAVAILABLE
Enter fullscreen mode Exit fullscreen mode

Let me know in the comments if you use it already or if you will in the future and what are your feedbacks about VError.

Top comments (1)

Collapse
 
zmrfzn profile image
Zameer Fouzan

i want to use this to throw & rethrow multi-level / multi-module errors , exclusively for retaining stacktrace.

brief summary:
I have 3-4 modules , and a custom error type.
if an error happens in module 4, i want to bubble the same to module 2 with the stack trace intact.

will this work for me ? are there any examples for this ?