express-api-problem

Automatically turns your thrown exceptions to the JSON response while conforming to API problem specification
An express package that lets you handle the API problems with ease. It provides a straightforward implementation of IETF Problem Specification and turns your thrown exceptions to be returned in the below format with the header of content type set to application/problem+json
{
"status": 403,
"type": "http://example.com/problems/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but the item costs 50.",
"instance": "http://example.net/account/12345/logs?id=233"
}
Where
title
is the summary of problemstatus
is the status codedetail
is human readable explanation specific to problemtype
is the absolute URI that identifies the type of probleminstance
is the absolute URI that identifies the specific occurrence of the problem
Installation
yarn add express-api-problem
Usage
Register the middleware
var ApiProblemHandler = require('express-api-problem/middleware');
app.use(ApiProblemHandler);
Throw exceptions while instantiating ApiProblem
having the following signature
var ApiProblem = require('express-api-problem');
throw new ApiProblem(statusCode, title, description, additionalDetail);
Add the mongoose plugin to automatically transform your model validation errors to API Problem
var mongooseValidator = require('express-api-problem/mongoose-validator');
yourSchema.plugin(mongooseValidator);
yourSchema.plugin(mongooseValidator, {
status: 400,
title: "Look before you submit!"
});
Examples
Throwing exception using only status code
throw new ApiProblem(400);
Providing description string
throw new ApiProblem(404, 'User not found', 'No user found against the given ID: 10');
Using object in description
throw new ApiProblem(400, 'Validation failed', {
name: 'Name field is required',
email: 'Invalid email given'
});
Adding additional detail to response
throw new ApiProblem(400, 'Insufficient Balance', 'You do not have enough balance to purchase the product', {
available_balance: 'USD 2000',
required_balance: 'USD 12422'
});
Contributing
Feel free to fork, enhance, create PR and lock issues.
License
MIT © Kamran Ahmed