Giter VIP home page Giter VIP logo

express-http-problem-details's Introduction

Conventional Commits Join the chat at https://gitter.im/pdmlab/express-http-problem-details

HTTP Problem Details for express

Based on http-problem-details (repository | npm) and http-problem-details-mapper (repository | npm), this library allows you to map your Node.js errors to HTTP Problem details according to RFC7807 by convention.

Installation

npm install express express-http-problem-details

or

yarn add express express-http-problem-details

Usage

express-http-problem-details provides a middleware which allows you to map custom Error instances to HTTP Problem Details documents according to RFC7807.

The details of the mapping itself are described in http-problem-details-mapper (repository | npm)

Example

The typical workflow in JavaScript/ES2015 with http-problem-details-mapper is this:

First, you implement an Error

class NotFoundError extends Error {
  constructor (options) {
    const { type, id } = options
    super()
    Error.captureStackTrace(this, this.constructor)

    this.message = `${type} with id ${id} could not be found.`
  }
}

Next, you extend the ErrorMapper class:

import { ProblemDocument } from 'http-problem-details'
import { ErrorMapper } from 'http-problem-details-mapper'

class NotFoundErrorMapper extends ErrorMapper {
  constructor() {
    super(NotFoundError)
  }

  mapError (error) {
    return new ProblemDocument({
      status: 404,
      title: error.message,
      type: 'http://tempuri.org/NotFoundError'
    })
  }
}

Finally, create an instance of ExpressMappingStrategy to hold the mappers and register everything in your app. Notice that the HttpProblemResponse must come last. A global error logger would precede it and forward the error to the next function.

import { HttpProblemResponse } from 'express-http-problem-details'
import { DefaultMappingStrategy, MapperRegistry } from 'http-problem-details-mapper'

const strategy = new DefaultMappingStrategy(
    new MapperRegistry()
      .registerMapper(new NotFoundErrorMapper()))


const server = express()

server.get('/', async (req, res) => {
  return res.send(new NotFoundError({type: 'customer', id: '123' }))
})
server.use(function logErrors (err, req, res, next) {
  console.error(err.stack)
  next(err)
})
server.use(HttpProblemResponse({strategy}))

server.listen(3000)

When GETting localhost:3000, the result will be like this:

HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 107
Content-Type: application/problem+json; charset=utf-8
Date: Wed, 24 Apr 2019 23:48:27 GMT
ETag: W/"6b-dSoRnzOA0Ls+QaHyomC8H+uv7GQ"
X-Powered-By: Express

{
    "status": 404,
    "title": "customer with id 123 could not be found.",
    "type": "http://tempuri.org/NotFoundError"
}

When just returning a return res.status(500).send();, you'll get a response like this:

HTTP/1.1 500 Internal Server Error
Connection: keep-alive
Content-Length: 67
Content-Type: application/problem+json; charset=utf-8
Date: Thu, 25 Apr 2019 00:01:48 GMT
ETag: W/"43-U3E8vFCP1+XTg1JqRHkrjQWiN60"
X-Powered-By: Express

{
    "status": 500,
    "title": "Internal Server Error",
    "type": "about:blank"
}

Running the tests

npm test

or

yarn test

Want to help?

This project is just getting off the ground and could use some help with cleaning things up and refactoring.

If you want to contribute - we'd love it! Just open an issue to work against so you get full credit for your fork. You can open the issue first so we can discuss and you can work your fork as we go along.

If you see a bug, please be so kind as to show how it's failing, and we'll do our best to get it fixed quickly.

Before sending a PR, please create an issue to introduce your idea and have a reference for your PR.

We're using conventional commits, so please use it for your commits as well.

Also please add tests and make sure to run npm run lint-ts or yarn lint-ts.

License

MIT License

Copyright (c) 2019 PDMLab

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

express-http-problem-details's People

Contributors

alexzeitler avatar dependabot[bot] avatar gitter-badger avatar mastermatt avatar tpluscode avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

express-http-problem-details's Issues

Request to use Response.json over Response.send(JSON.stringify...)

I'm curious if decision to use .send instead of .json was intentional for some reason:

response.send(JSON.stringify(problem))

The issue being, Expresses Response.json use app settings for the replacer, escape, and spaces settings of JSON.stringify and stringifying the payload directly bypasses these options.

If it doesn't make a difference to the functionality of this lib, I'd be happy to open a PR.

Errors passed to next are not mapped

Current

Express has a built-in way for returning errors from any middleware with the next(error) call. It appears that errors returned this way do not get converted into problem+json because the handler is an ordinary middleware callback.

Desired

Any error returned in the standard way should be intercepted and converted into a mapped problem document.

Proposal

I think that following best practices of express, the 4-parameter error callback could be used instead. Thus the code can actually be simplified. Here's my implementation:

import { IMappingStrategy } from 'http-problem-details-mapper'

class HttpProblemResponseOptions {
  public strategy: IMappingStrategy;
}

export function HttpProblemResponse (options: HttpProblemResponseOptions) {
  const { strategy } = options

  return (err, req, res, next) => {
    let problem = strategy.map(err)

    res.statusCode = problem.status
    res.setHeader('Content-Type', 'application/problem+json')
    res.send(JSON.stringify(problem))
  }
}

The only difference is that it must be the last app.use call when setting up express

const server = express()
-server.use(HttpProblemResponse({strategy}))

server.get('/', async (req: express.Request, res: express.Response): Promise<any> => {
  return res.send(new NotFoundError({type: 'customer', id: '123' }))
})
+server.use(HttpProblemResponse({strategy}))

Missing error mapper crashes an app

I just bumped into a problem that when a mapper is not registered, the handler will break and express dies.

The problem is scattered across multiple places. In this end, the mapping strategy is inhonest about the return value from map. The typing says that it will be a ProblemDocument yet an undefined is also possible.

https://github.com/PDMLab/express-http-problem-details/blob/master/src/ExpressMappingStrategy.ts#L16

I suggest strict: true in tsconfig.json to prevent such subtle errors.


Second, it actually falls to the registry that it does not find a mapper even when the default mapper is used.

I propose to always return the default mapper when a more specific cannot be found. I think it could also be possible to walk up the prototype chain to sort of emulate polymorphism.

Map response headers

There are cases where I would like to set additional headers on a problem details response. For example:

For now this is my workaround, which relies on the errors thrown or passed to next having a valid headers property, and feels a bit hacky:

app.use((err, req, res, next) => {
  if (err.headers && (typeof err.headers === 'object')) {
    for (let [key, val] of Object.entries(err.headers)) {
      res.header(key, val);
    }
  }
  next(err);
});

app.use(HttpProblemResponse({strategy}));

I think it would be better if we could somehow explicitly include response headers when mapping specific error types, such that those headers are then set on the response sent by HttpProblemDetailsMiddleware().

Does ExpressMappingStrategy belong here?

I'm not sure how specific the ExpressMappingStrategy is to express actually?

I think right now that maybe it belongs to the http-problem-details-mapper package.

Slack invite

By the way, I wanted to join your Slack but the invitation link expired.

That said, maybe it's more hassle-free to set up a gitter community? It is more readily accessible to GitHub users than yet another Slack channel.

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.