⚡
light
  • light
  • guides
    • getting started
    • server vs serverless
    • routes
    • models
    • factories
    • routing
    • plugins
    • middleware
    • query
    • params
    • global
    • error handling
    • hot module reloading (TODO)
    • databases (TODO)
      • mongoose
      • objection/knex
    • testing (TODO)
      • ava
      • jest
    • deployments (TODO)
      • runkit
      • aws
      • now
      • heroku
      • server
      • google cloud
      • azure
      • netlify
    • misc (TODO)
      • apollo/graphql
  • api
    • server({ routes, opts }): object
    • params(path, url): Promise<object>
    • boom
      • Coming soon
    • micro
      • Coming soon
      • Coming soon
      • Coming soon
      • Coming soon
      • Coming soon
      • Coming soon
Powered by GitBook
On this page
  • Introduction
  • Usage
  • Error Object

Was this helpful?

  1. guides

error handling

PreviousglobalNexthot module reloading (TODO)

Last updated 5 years ago

Was this helpful?

Introduction

Error handling is done mostly by throwing a new Error. Each route is wrapped with a try/catch block so that you can safely throw at any point. The reason throwing for errors is nice is because it allows you to escape from any point in your code!

Usage

Simply import and throw it at any point. createError will create a boom error resulting in a pretty JSON output.

const { createRoute, createError } = require('light');

const { route } = createRoute('error');

module.exports = route(() => {
  throw createError(401, 'sorry, you cannot access this route');
  return 'it will not get to me :(';
});

This will result in JSON which looks like this:

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "sorry, you cannot access this route"
}

Error Object

You can also throw a standard JavaScript Error object with a message and statusCode (defaults to 500).

const err = new Error('Rate limit exceeded')
err.statusCode = 429
throw err
createError