http-handler-response
Built with ❤︎ by Hiukky
A simple handler to standardize and handle HTTP request errors and responses in API's.
Installation
# Using NPM npm i http-handler-response # Using YARN yarn add http-handler-response
Using
The http-handler-response provides three main functions. createException
, createResponse
and handlerError
.
createException
The createException
function is the function responsible for formulating your return messages in unsuccessful requests. It follows the RFC-7807 standard.
Parameters
// Object with response specifications payload: code: number | string // HTTP status code 4xx to 5xx type?: string // URL for a document describing the error condition title?: string // Short and descriptive information detail: string // Legible error description instance?: string // URI exclusive for or specific error
Example
async { try const user = await User if !user return user catch error }
Response
status: 404 title: 'Not found' detail: 'The user informed is not registered.' instance: '/users/1' type: 'https://example.com/docs/users'
createResponse
The createResponse
function is the function responsible for formulating your return messages in successful requisitions.
Parameters
// HTTP Response Object response: object // Object with response specifications payload: code: number | string // HTTP status code 1xx to 3xx title?: string // Short and descriptive information message?: string // Legible action response instance: string // URI exclusive for or specific error data: object // Back Data
Example
async { try const data = request const user = username = dataname useremail = dataemail await user return catch error }
Response
status: 201 title: 'Created' message: 'Successful registered user.' data: id: 1 name: 'User' email: 'user@email.com'
handlerError
http-handler-response has custom handlers for handling errors for various web frameworks, such as AdonisJs
,Express
and KoaJs
. You can use it within your catch
block on each call or create custom middleware responsible for handling exceptions globally in the HTTP context.
Example
async { try // Your code.. catch error }