import Problem from 'api-problem'// HTTP defaultsnew Problem(404)//=> { status: '404', title: 'Not Found', type: 'https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404' }// override defaultsnew Problem(404, 'Oops! Page Not Found')//=> { status: '404', title: 'Oops! Page Not Found', type: 'https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404' }// custom valuesnew Problem(403, 'You do not have enough credit', 'https://example.com/probs/out-of-credit')//=> { status: '403', title: 'You do not have enough credit', type: 'https://example.com/probs/out-of-credit' }// additional detailsnew Problem(403, 'You do not have enough credit', 'https://example.com/probs/out-of-credit', { detail: 'Your current balance is 30, but that costs 50.'
Method : <object>toObject()
returns an object containing all the properties including: (status, title, type, members)
const prob = new Problem(403, 'You do not have enough credit', 'https://example.com/probs/out-of-credit', { user_id: 'x123' })prob.toObject() //=> { status: 403, title: 'You do not have enough credit', type: 'https://example.com/probs/out-of-credit', user_id: 'x123' }
Method : <string>toString()
returns a simplified, human-readable string representation
const prob = new Problem(403, 'You do not have enough credit', 'https://example.com/probs/out-of-credit')prob.toString() //=> [403] You do not have enough credit ('https://example.com/probs/out-of-credit')
import http from 'http'import Problem from 'api-problem'let response = new http.ServerResponse()Problem.send(response)
Express Middleware
A standard connect middleware is provided. The middleware intercepts Problem objects thrown as exceptions and serializes them appropriately in the HTTP response while setting the Content-Type response header to application/problem+json
import express from 'express'import Problem from 'api-problem'import Middleware from 'api-problem/lib/middleware'const app = express()app.get('/', (req, res) => { throw new Problem(403)})app.use(Middleware)
//=> { status: '403', title: 'You do not have enough credit', type: 'https://example.com/probs/out-of-credit', detail: 'Your current balance is 30, but that costs 50.', instance: '/account/12345/msgs/abc', balance: 30, accounts: ['/account/12345', '/account/67890'] }