0.0.1 • Published 3 years ago

@geniucode/terminator v0.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

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 TypesStatus CodeDefault Error
BadRequestError400[DEFAULT-ERROR] Bad Request
NotAuthorizedError401[DEFAULT-ERROR] Not Authorized
PaymentRequiredError402[DEFAULT-ERROR] Payment Is Required
ForbiddenError403[DEFAULT-ERROR] Forbidden
NotFoundError404[DEFAULT-ERROR] Not Found
InvalidHttpMethodError405[DEFAULT-ERROR] Invalid HTTP Method
MethodNotAllowedError405[DEFAULT-ERROR] Method Not Allowed
ProxyAuthRequiredError407[DEFAULT-ERROR] Proxy Authentication Required
RequestTimeoutError408[DEFAULT-ERROR] Request Timeout
ConflictError409[DEFAULT-ERROR] Conflict Has Been Found
DuplicateIdConflictError409[DEFAULT-ERROR] Duplicate Id
LargePayloadError413[DEFAULT-ERROR] Payload Too Large
UnsupportedMediaTypeError415[DEFAULT-ERROR] Unsupported Media Type
ValidationError (Unprocessable Entity)422[DEFAULT-ERROR] There Was A Validation Error
ProtocolUpgradeRequiredError426[DEFAULT-ERROR] Protocol Upgrade Required
TooManyRequestsError429[DEFAULT-ERROR] Too Many Requests
InternalServerError500[DEFAULT-ERROR] Internal Server
DatabaseConnectionError500[DEFAULT-ERROR] Database Connection
NotImplementedError501[DEFAULT-ERROR] Not implemented, server does not support the functionality required to fulfill the request.
GatewayTimeoutError504[DEFAULT-ERROR] Gateway Timeout
ServiceUnavailableError503[DEFAULT-ERROR] Service Unavailable
HttpVersionNotSupportedError505[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.