Coder Social home page Coder Social logo

mamsoudi / merror Goto Github PK

View Code? Open in Web Editor NEW
29.0 1.0 0.0 398 KB

A REST-friendly Express Middleware for HTTP error handling

Home Page: http://masoudmirzaei.ir/merror

License: MIT License

JavaScript 5.73% TypeScript 94.27%
express expressjs express-middleware error-handling error-messages nodejs

merror's Introduction

Merror

Build Status bitHound Dependencies bitHound Dev Dependencies bitHound Code bitHound Overall Score

Merror

Developing REST APIs with Express, I was always looking for a clean way to send HTTP error responses along with the data I wanted, not only to allow clients to know which error has happened but to provide the information I wanted.

Express allows you to handle errors but doesn't return Error objects yet renders pages containing error information which is not so useful when developing REST APIs. Error information should be sent to the clients in JSON format so that they can process it and show it to users. So....

Here's Merror (/ˈmɪrə/). A simple wrapper around JavaScript Error objects with a middleware for Expressjs. Merror allows you to define a new HttpError object when you need in your controller. The object then will be passed to the middleware to be processed and sent to the client.

Usage

Using Merror is easy and straight-forward. Install express-merror using NPM or Yarn and import Merror and MerrorMiddlware in your application.

$ npm install --save express-merror
// If using TypeScript and ES6:
import { Merror, MerrorMiddleware } from 'express-merror';

// If using JS/RequireJS
const MerrorModule = require('express-merror');
const Merror = MerrorModule.Merror;
const MerrorMiddleware = MerrorModule.MerrorMiddleware;

Register MerrorMiddleware in your Expressjs application as a middleware after registering router module and start constructing Merror Objects whenever you hit an error in your controllers. Let's see an example:

const express = require("express");
const cors = require("cors");
const app = express();
const router = express.Router();

// Some other middleware
app.use(cors());

// Register Routing Module
app.use("/", router);

// Router
router.post("/profile", function(req, res) {
  // Pay attention that we should wrap our error object
  // with next() in order to make it travel to our middleware
  // which is registered after router module
    return next(new Merror(401, "Unauthorized Access! Custom Message!", {code: 1001,status: "REFRESH_TOKEN"} ));
});


// Merror Middleware
app.use(MerrorMiddleware());

// Router Module
app.listen(3000, () => console.log("Example app listening on port 3000!"));

If we make a request to http://localhost:3000/profile we will see this in the body of the response:

{
  "success": false,
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "Unauthorized Access!",
  "properties": {
    "code": 1001,
    "status": "REFRESH_TOKEN"
  }
}

NOTE: Please pay attention that you should register the middleware after registering routes and also wrap constructed error with next() function and return it in order for Merror to work properly.

API

new Merror(statusCode, message, [properties])

Creates a new Merror object with given statusCode and message. You're free to take control of what you pass as properties it will be included in the response.

app.post("/login", function(req, res) {
    return next(new Merror(500, "Internal Server Error", {code: 1021,status: "USER_NOT_FOUND"} ));
});

Assuming we have express-validator middleware in our application we can do this:

app.post("/login", function(req, res) {
  req.assert("email", "Provided email is not correct").isEmail().notEmpty();
  req.assert("password", "Password is not valid").isLength({ min: 8 }).notEmpty();

  const errors = req.validationErrors(true);

  if (errors) {
    return next(new Merror(403, "Authentication Failed. Invalid Email or Password.", errors));
  }

  // Rest of our code to find user, etc.
});

Now if we POST an invalid email to this route we can see this in the response:

{
    "success": false,
    "statusCode": 403,
    "error": "Forbidden",
    "message": "Authentication Failed. Invalid Email or Password.",
    "properties": {
        "email": {
            "location": "body",
            "param": "email",
            "msg": "Provided email is not correct",
            "value": false
        }
    }
}

MerrorMiddleware()

Returns a simple handler that takes errors constructed in our router and sends a response with corresponding statusCode, message and properties if provided.

// Router Module
app.get('/', (req, res) => next(new Merror(404, "Not Found!")))

// Register Middleware here after all routes
app.use(MerrorMiddleware());

License

This project is licensed under MIT. Feel free to fork, change and use it however you like.

Contribution

If you feel there's something that could be better in this module make sure to fork, make changes and make a new PR with full description of what you've changed. I'll make sure to review it.

merror's People

Contributors

mamsoudi 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

Watchers

 avatar

merror's Issues

Chore(deps): Update dependencies

Is your feature request related to a problem? Please describe.
Currently this repository doesn't support the latest changes in express and Typescript.

Describe the solution you'd like
Update dependencies and ensure everything works perfectly.

Chore(misc): Unit testing and testing environment

Is your feature request related to a problem? Please describe.
In order to be able to test the features we need an environment in which we'll be able to test the code.

Describe the solution you'd like
In order to test the functionality we can add Unit tests and we can initialise a testing environment.

Describe alternatives you've considered
Having npm serve run a testable API which users can run to test and see the results.

Console output

Hi,

is there any way to disable console output on error or use a custom logging function?

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.