@geniucode/terminator
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

Geniucode Terminator

The purpose of this package is to handle errors. It can be used to log and throw error ( have look at the error types bellow ), and an errorHandler for thrown error can be used to return a response.

Install

npm i --save @geniucode/terminator

Versions that can be used

  0.0.2 => npm i --save @geniucode/terminator@0.0.2

API Documentation

Available Error Types Status Code Default Error
BadRequestError 400 [DEFAULT-ERROR] Bad Request
NotAuthorizedError 401 [DEFAULT-ERROR] Not Authorized
PaymentRequiredError 402 [DEFAULT-ERROR] Payment Is Required
ForbiddenError 403 [DEFAULT-ERROR] Forbidden
NotFoundError 404 [DEFAULT-ERROR] Not Found
InvalidHttpMethodError 405 [DEFAULT-ERROR] Invalid HTTP Method
MethodNotAllowedError 405 [DEFAULT-ERROR] Method Not Allowed
ProxyAuthRequiredError 407 [DEFAULT-ERROR] Proxy Authentication Required
RequestTimeoutError 408 [DEFAULT-ERROR] Request Timeout
ConflictError 409 [DEFAULT-ERROR] Conflict Has Been Found
DuplicateIdConflictError 409 [DEFAULT-ERROR] Duplicate Id
LargePayloadError 413 [DEFAULT-ERROR] Payload Too Large
UnsupportedMediaTypeError 415 [DEFAULT-ERROR] Unsupported Media Type
ValidationError (Unprocessable Entity) 422 [DEFAULT-ERROR] There Was A Validation Error
ProtocolUpgradeRequiredError 426 [DEFAULT-ERROR] Protocol Upgrade Required
TooManyRequestsError 429 [DEFAULT-ERROR] Too Many Requests
InternalServerError 500 [DEFAULT-ERROR] Internal Server
DatabaseConnectionError 500 [DEFAULT-ERROR] Database Connection
NotImplementedError 501 [DEFAULT-ERROR] Not implemented, server does not support the functionality required to fulfill the request.
GatewayTimeoutError 504 [DEFAULT-ERROR] Gateway Timeout
ServiceUnavailableError 503 [DEFAULT-ERROR] Service Unavailable
HttpVersionNotSupportedError 505 [DEFAULT-ERROR] HTTP Version Not Supported

NOTES

RequestValidationError is different than ValidationError, RequestValidationError gets an array as an argument

ValidationError Might occurs for example on cases as the following: This username already exists

NotFoundError Item/Resource not found

Usage Demo 1 - Throw an Error without Log

import { TErrors, TUtils} from '@geniucode/terminator';

try{
    throw new TErrors.BadRequestError("Demo error Message");
    // Or throw a default message by using:
    throw new TErrors.BadRequestError();
}
catch(error: any){
    TUtils.throwError(error);
}

Usage Demo 2 - Throw an Error and Log

import { TErrors, TUtils} from '@geniucode/terminator';

try{
    throw new TErrors.BadRequestError("Check your fields");
}
catch(error: any){
    TUtils.throwErrorAndLog(error);
    // Error output message:
    // Check your fields


    // You can provide a prefix message for the error as the following
    TUtils.throwErrorAndLog(error, '[Prefix-Message]-Your request is invalid'); 
    // Error output message:
    // [Prefix-Message]-Your request is invalid Check your fields
}

Usage via app.ts file

import { TMiddlewares } from '@geniucode/terminator';

// Handle the thrown Errors
// and will end the response with the right status code depends on Error Type
app.use(TMiddlewares.errorHandler); 

Usage Example from a route in Express

  async (req: Request, res: Response) => {

    const {ticket, status} = req.body;
    const sessionInfo = {ticket,status};

    let session;
    try {
      session = await Session.build(sessionInfo).save();
      const session = await Session.build(sessionInfo).save();
      httpResponse.created(res, session, 'Session Created successfully');
    } catch (error: any) {
// **** VERY IMPORTANT ****
// Notice here we are throwing always an error of type ConflictError, 
// even though a different type of error might been thrown
      const errorMsg = `Unable to create session:: ${error?.message}`;
      throw new TErrors.ConflictError(errorMsg);
    }
  }

Usage Example from a route in Express

  async (req: Request, res: Response) => {

    const {ticket, status} = req.body;
    const sessionInfo = {ticket,status};

    let session;
    try {
      session = await Session.build(sessionInfo).save();
      const session = await Session.build(sessionInfo).save();
      httpResponse.created(res, session, 'Session Created successfully');
    } catch (error: any) {

// ************ Very Important ************
// Thrown error is catched by app.use(TMiddlewares.errorHandler) from app.ts file
      const errorMsg = `Unable to create session:: ${error?.message}`;
      throw new TErrors.ConflictError(errorMsg);
    }
  }

An example Of how you would replace an existing code to the new one

import { TErrors, TUtils } from '@geniucode/terminator';

async (req: Request, res: Response) => {
    const { message, agent, ticket } = req.body;

    try {
      if (!agent || !ticket) {
        throw new TErrors.BadRequestError('Something went wrong');
        // throw new BadRequestError('Something went wrong');
      }
      
    } catch (error: any) {
      
      TUtils.throwErrorAndLog(error, 'Novelty-Error-service | ');
      // TUtils.throwErrorAndLog is replacing all of the code bellow

      // logger.error(error?.message);
      // if (error instanceof BadRequestError) {
      //   throw new BadRequestError('Novelty-Error-service | ' + error?.message);
      // } else {
      //   throw new Error('Novelty-Error-service | ' + error?.message);
      // }
    }
  }

Dependencies

  • @geniucode/chokidar

Contributors

  • Esmat Nawahda

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.

License

Please see License File for more information.

Readme

Keywords

none

Package Sidebar

Install

npm i @geniucode/terminator

Weekly Downloads

74

Version

0.0.1

License

ISC

Unpacked Size

111 kB

Total Files

84

Last publish

Collaborators

  • geniucode-dev