0.2.0 • Published 8 years ago

some-http-error v0.2.0

Weekly downloads
4
License
MIT
Repository
github
Last release
8 years ago

some-http-error

Build Status Coverage Status

A javascript error creator for some often used HTTP error

Getting started

Install

$ npm install some-http-error

Usage

You can use this module in any node.js web frameworks, such as express

In controllers

var HttpError = require('some-http-error');

function handle(req, res, next) {

  var userId = req.query.id;

  // If some error happened
  if (!userId) {
    // You can pass it to error handling middleware
    next(new HttpError.BadRequestError('"id" is not set'));
    // Or just throw it!
    // throw new HttpError.BadRequestError('"id" is not set'));
  }

  // In promise
  User.findById(userId).then(user => {

    if (!user) {
      // Not found, just throw it!
      throw new HttpError.NotFoundError('User not found');
    }

    // ...

    // Don't forget to catch the error, and pass it to error handling middleware
  }).catch(next);
}

In error handling middleware

var HttpError = require('some-http-error');

function errorHandle(err, req, res, next) {

  if (err instanceof HttpError) {
    // If it is an HttpError, send the HTTP status code and error message
    res.sendStatus(err.statusCode).json(err.message);
  } else {
    // Otherwise send 500
    res.sendStatus(500).json(err.message);
  }

API

HttpError(statusCode, message)

The basic HttpError object constructor, and you can construct HttpError like this:

new HttpError(404)
new HttpError(404, 'This page is not found')
HttpError.BadRequestError(message)
  • statusCode: 400
  • message: Bad Request
HttpError.UnauthorizedError(message)
  • statusCode: 401
  • message: Unauthorized
HttpError.ForbiddenError(message)
  • statusCode: 403
  • message: Forbidden
HttpError.NotFoundError(message)
  • statusCode: 404
  • message: Not Found
HttpError.MethodNotAllowedError(message)
  • statusCode: 405
  • message: Method Not Allowed

License

MIT

0.2.0

8 years ago

0.1.0

8 years ago

0.0.2

8 years ago

0.0.1

8 years ago