1.2.0 • Published 7 months ago

errors-express v1.2.0

Weekly downloads
-
License
ISC
Repository
-
Last release
7 months ago

Errors for Express

Easy error handling for Express APIs.

NPM NPM NPM

Installation

Install together with express

npm i express errors-express

Usage

Import the error handler middleware and place it at the end of the middleware stack. Any error (operational or not) thrown by a controller is handled and sent to the client.

Use the handler with a callback to perform extra actions such as logging. Callback receives the error and the request object.

Use guards to return a custom error response after not found or not allowed methods requests.

import express from 'express';
import errorHandler, { Errors, Guards } from 'errors-express';

const app = express();

app.get('/protected', async (req, res) => {
  throw Errors.Unauthorized('You must first sign in');
});

app.all('*', Guards.NotFound());

app.use(errorHandler((error, req) => {
  console.log(`[${req.method} ${req.url}] ${error.message}`);
}));

app.listen(process.env.PORT || 3000);

Errors

The base error class used by the package is HttpError. Send optional errorCode for error identification (useful for error translation).

HttpError(statusCode, message, errorCode?)

Default errors are provided by the package, just include optional message and errorCode.

import { HttpError, Errors } from 'errors-express';

throw new HttpError(400, 'Invalid request', 'MISSING_PSWD');

throw Errors.NotFound();
throw Errors.Forbidden('You cannot do this');
ErrorstatusCodeDefault message
BadRequest400The request syntax is invalid
Unauthorized401The authentication credentials are invalid
Forbidden403You are not allowed to use this resource
NotFound404This resource does not exist
MethodNotAllowed405This method is not allowed for this resource
Conflict409There is a conflict with the current state of the resource
Unprocessable422The request is unprocessable
TooManyRequests429The maximum number of requests has been exceeded
InternalServer500An internal server error occurred

Guards

Guards automatically return an error if none of the previous handlers are called.

import { Guards } from 'errors-express';

app.get('/resource', ResourceController);
app.all('/resource', Guards.MethodNotAllowed());
app.use(Guards.NotFound()),

Only MethodNotAllowed and NotFound are available.

1.2.0

7 months ago

2.0.0

7 months ago

1.1.0

10 months ago

1.0.2

2 years ago

1.0.3

2 years ago

1.0.1

3 years ago

1.0.0

3 years ago