1.0.0 • Published 3 years ago

dl-exception-handler v1.0.0

Weekly downloads
5
License
Altorum Leren Pvt...
Repository
-
Last release
3 years ago

Handle Express Exceptions

Handle exceptions in express with i18n support. The exception handler middleware can be easily plugged into any express application and catch any exceptions and show a formatted message to the client.

Dependencies

The library has two peer dependencies which the application should be having installed:

  • dotenv
  • express

Usage

The library can be used out of the box without much of a setup.

  1. Install the package
  2. Import the HttpException module from the library in the Application file.
import { HttpException } from 'exception-handler';
HttpException.configure();
  1. If you want to have support for Internationalization(i18n) in the response, You will need to give the folder path to where the language resource files are saved.
import { HttpException } from 'exception-handler';
HttpException.configure(path.join(__dirname, './i18n');

Errors Exposed

  • badRequest
  • serverError
  • unauthorizedError
  • notFoundError
import { unauthorizedError, notFoundError, badRequest, serverError } from 'exception-handler';

badRequest(); // sends out english responses
badRequest('fr'); // sends out french reposes

Setup I18N

To add new language, just create a json file in the folder specified during configuration.

-| i18n
---| en.json
---| fr.json

Put the following contents in the file and save.

{
  "bad_request": "Mauvaise Demande",
  "server_error": "Erreur Interne du Serveur",
  "unauthorized": "Non autorisé",
  "forbidden": "Interdit"
}

You can add multiple languages in a similar way, just have to change the value of the keys in the json file and put it in another json file again in the folder specified during configuration.

Complete Example

import express, { Request, Response, NextFunction } from 'express';
import { HttpException, handleExceptions, unauthorizedError, notFoundError } from 'exception-handler';
import path from 'path';

const app = express();

HttpException.configure(path.join(__dirname, './i18n')); //configure the language files

app.get('/', async (_req: Request, _res: Response, next: NextFunction) => {
  next(unauthorizedError('es')); // pass error in controller
});

app.use(handleExceptions); // use the handle exceptions middleware
1.0.0

3 years ago