http-error-middleware v0.0.10
http-error-middleware
http-error-middleware is a package that simplifies error handling in Express applications. It provides an easy way to generate and manage specific HTTP errors using middleware, making your code clearer and ensuring a consistent structure for error responses.
This package allows you to throw errors with specific HTTP status codes and custom messages, then handle them centrally in your application using a single middleware.
Installation
You can install the package from npm using the following command:
npm install http-error-middlewareBasic Usage
Set Up Middleware in Your Express Application
First, you need to import and use the middleware provided by http-error-middleware in your Express app.
import express from 'express'
// Import the package
import { httpErrorMiddleware } from 'http-error-middleware'
const app = express()
// Define your app routes.
app.get('/', (req, res) => {
res.status(200).json({ message: 'Hello world' })
})
// Use the middleware to handle errors.
app.use(httpErrorMiddleware())
// Other middleware for handling errors can go here.
// Start the server.
app.listen(3000, () => {
console.log('Server running')
})httpErrorMiddleware settings
The middleware offers some configurations to customize the error response, which are optional.
import express from 'express'
import { httpErrorMiddleware } from 'http-error-middleware'
const app = express()
//Other Express app config
app.use(httpErrorMiddleware({
destructure: false,
statusCodeOnResponse: false
}))If you want the error details to be placed at the root of the response body, set the "destructure" flag to true.
If you want the status code sent to be in the response body, set the "statusCodeOnResponse" flag to true.
The default settings is as follows:
{
"destructure": false,
"statusCodeOnResponse": true
}Throw Errors Where You Need Them
You can throw HTTP errors anywhere in your application using the HttpError class provided by the package. Here's a simple example to throw a 400 Bad Request error.
import { HttpError } from 'http-error-middleware'
if (condition) HttpError.badRequest('Email and/or password are wrong')This code will throw an error that gets handled by the middleware, and the response will look like this:
{
"message": "Email and/or password are wrong",
"statusCode": 400 // This property will be removed this if you set the "statusCodeOnResponse" flag to false.
}Errors with Additional Details
If you need to send more details with the error (e.g., information about which form field is incorrect), you can do it like this:
import { HttpError } from 'http-error-middleware'
if (condition) HttpError.badRequest('Email and/or password are wrong', { fieldName: "Error message", ...moreErrors })This will generate a response with additional error details:
{
"message": "Email and/or password are wrong",
"details": {
"fieldName": "Error message",
"fieldName2": "Error message"
},
"statusCode": 400 // This property will be removed this if you set the "statusCodeOnResponse" flag to false.
}If you have the "destructure" flag set, the message will be displayed like this:
{
"message": "Email and/or password are wrong",
"fieldName": "Error message",
"fieldName2": "Error message",
"statusCode": 400 // This property will be removed this if you set the "statusCodeOnResponse" flag to false.
}Available HTTP Error Methods
The package provides methods to generate common HTTP errors with specific status codes. Here are the available methods:
Client Errors (4xx)
HttpError.badRequest(message: string, details?: object)- Throws a
400 Bad Requesterror with the provided message and optional details.
- Throws a
HttpError.unauthorized(message: string, details?: object)- Throws a
401 Unauthorizederror with the provided message and optional details.
- Throws a
HttpError.paymentRequired(message: string, details?: object)- Throws a
402 Payment Requirederror with the provided message and optional details.
- Throws a
HttpError.forbidden(message: string, details?: object)- Throws a
403 Forbiddenerror with the provided message and optional details.
- Throws a
HttpError.notFound(message: string, details?: object)- Throws a
404 Not Founderror with the provided message and optional details.
- Throws a
HttpError.methodNotAllowed(message: string, details?: object)- Throws a
405 Method Not Allowederror with the provided message and optional details.
- Throws a
HttpError.notAcceptable(message: string, details?: object)- Throws a
406 Not Acceptableerror with the provided message and optional details.
- Throws a
HttpError.proxyAuthenticationRequired(message: string, details?: object)- Throws a
407 Proxy Authentication Requirederror with the provided message and optional details.
- Throws a
HttpError.requestTimeOut(message: string, details?: object)- Throws a
408 Request Timeouterror with the provided message and optional details.
- Throws a
HttpError.conflict(message: string, details?: object)- Throws a
409 Conflicterror with the provided message and optional details.
- Throws a
Server Errors (5xx)
HttpError.internalServerError(message: string, details?: object)- Throws a
500 Internal Server Errorwith the provided message and optional details.
- Throws a
HttpError.notImplemented(message: string, details?: object)- Throws a
501 Not Implementederror with the provided message and optional details.
- Throws a
HttpError.badGateway(message: string, details?: object)- Throws a
502 Bad Gatewayerror with the provided message and optional details.
- Throws a
HttpError.serviceUnavailable(message: string, details?: object)- Throws a
503 Service Unavailableerror with the provided message and optional details.
- Throws a
HttpError.gatewayTimeOut(message: string, details?: object)- Throws a
504 Gateway Timeouterror with the provided message and optional details.
- Throws a
Custom Error
HttpError.custom(message: string, statusCode: number, details?: object)- Throws a custom error with a specified
statusCode(for errors not covered by the predefined methods) and optional details.
- Throws a custom error with a specified
Each of these methods generates a response with an appropriate HTTP status code, a message, and optionally, additional details.
Benefits
Consistency: Centralize error handling in a single middleware. Clarity: Easily create and throw HTTP errors with clear and specific messages. Extensibility: Add additional details to errors to provide more context, such as information about specific fields.