npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@geniucode/terminator

v0.0.1

Published

GeniuCode Terminator Package - To handle different type of errors

Downloads

108

Readme

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/[email protected]

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.