Git Product home page Git Product logo

throw.js's Introduction

throw.js

An HTTP Error collection to use in your next REST API.

Installation

npm install --save throw.js

or

yarn add throw.js

Example

const express = require("express");
const app = express();
const { NotFound } = require("throw.js");
const logger = require("winston");

app.get("/", (req, res, next) => {
    next(new NotFound());
});

app.use((err, req, res, next) => {
    logger.error(err);

    if (req.app.get("env") !== "development" && req.app.get("env") !== "test") {
        delete err.stack;
    }

    res.status(err.statusCode || 500).json(err);
});

app.listen(3000);

Custom Errors

const { CustomError } = require("throw.js");

throw new CustomError(message, statusCode?, errorCode?, originalError?);

Parameters:

  • message[optional]: Detailed message of this error
  • statusCode[optional]: The HTTP Status number to return
  • errorCode[optional]: An internal unique code identifier of this error

Stacking Errors

const { CustomError } = require("throw.js");

try {
    // throws an error
} catch (e) {
    // Pass the error as a parameter to keep its original stack trace
    throw new CustomError(message, statusCode, errorCode, e);
}

Errors

All of the classes below have all parameters set up by default, based on RFC7231. But you can override the message and the errorCode to fit your for personal needs.

400 Bad Request

BadRequest(message?, errorCode?, originalError?);

401 Unauthorized

Unauthorized(message?, errorCode?, originalError?);

402 Payment Required

PaymentRequired(message?, errorCode?, originalError?);

403 Forbidden

Forbidden(message?, errorCode?, originalError?);

404 Not Found

NotFound(message?, errorCode?, originalError?);

405 Method Not Allowed

MethodNotAllowed(message?, errorCode?, originalError?);

406 Not Acceptable

NotAcceptable(message?, errorCode?, originalError?);

407 Proxy Authentication Required

ProxyAuthenticationRequired(message?, errorCode?, originalError?);

408 Request Timeout

RequestTimeout(message?, errorCode?, originalError?);

409 Conflict

Conflict(message?, errorCode?, originalError?);

410 Gone

Gone(message?, errorCode?, originalError?);

422 Unprocessable Entity

UnprocessableEntity(message?, errorCode?, originalError?);

424 Failed Dependency

FailedDependency(message?, errorCode?, originalError?);

500 Internal Server Error

InternalServerError(message?, errorCode?, originalError?);

501 Not Implemented

NotImplemented(message?, errorCode?, originalError?);

502 Bad Gateway

BadGateway(message?, errorCode?, originalError?);

503 Service Unavailable

ServiceUnavailable(message?, errorCode?, originalError?);

504 Gateway Timeout

GatewayTimeout(message?, errorCode?, originalError?);

505 HTTP Version Not Supported

HttpVersionNotSupported(message?, errorCode?, originalError?);

511 Network Authentication Required

NetworkAuthenticationRequired(message?, errorCode?, originalError?);

TODO

  • Implement more Error Classes

throw.js's People

Contributors

kbariotis avatar lipis avatar sathishkumarso avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

throw.js's Issues

2.1.0 name changes are a breaking change over 2.0.0

I'm getting a lot of error messages that look like:

throwjs.notFound is not a function

๐Ÿ˜ž
It might be worthwhile reverting for a 2.2.0 release and rerelease the change with a new major version 3.0.0. Though I'll probably just lock down on 2.0.0 for now.

Error "message" not serialized by Express and not returned

Hello,

in the example code the error middleware returns the error like this:

res.status(err.statusCode || 500).json(err);

Unfortunately .json() doesn't serialize the error object returned by throw.js. The returned JSON in this example would be:

{
    "name": "NotFound",
    "statusCode": 404,
    "errorCode": 404
}

The "message"-property is missing.

Solution: To return the complete error object (including "message"-property) I use this instead:

res.set({ 'content-type': 'application/json' }).status(err.statusCode || 500).send(JSON.stringify(err, Object.getOwnPropertyNames(err)))

Source

Can this JSON serialization behaviour maybe implemented in throw.js?

Thanks!

Best practice showing flashmessages?

Hi,

How would you implement this for use with flashmessages?

Is it possible to, let say, redirect('back'), show a flash message but keep the status code?
For example a guest navigates to a secure admin page, so you redirect him to the login page show a message ('you need to have permission' or something) but keep the status 403?

Test issue

this is a test issue for testing purposes

Wrap previous Error

Add a previous Error on throw.js engine.

errors.BadRequest(err, 'Error on MongoDB');

example:

const errors = require('throw.js');
const mongoose = require('mongoose');
const User = mongoose.model('user');

app.get('/', (req, res, next) => Promise.resolve().then(() => {
  let {query} = req;
  if (!query.id) {
    throw errors.BadRequest('Missing id in query');
  }
  User.findOne({id: query.id}).exec().then(user => {
     req.user = user;
     next();
  }).catch(err => {
     // TODO - wrap MongoDB Error
     throw errors.BadRequest(err, 'Error on MongoDB');
  });
}).catch(err => next(err)));

You can concat the messagens:

module.exports = function BadRequest(err, message, errorCode) {
   if ('string' === typeof err) {
      errorCode = message;
      message = err;
      err = this;
   } else if (err instanceOf Error) {
      message = (message || '') + ' ' + err.message;
   }

  Error.captureStackTrace(err, this.constructor);

  this.name = this.constructor.name;
  this.message = message || 'Bad Gateway';
  this.status = this.statusCode = 502;
  this.errorCode = errorCode || 502;
};

require('util').inherits(module.exports, Error);

Typo on custom error call

On lib/index.js the customerror require is with only E capitalized, but the filename has C and E capitalized.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.