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

@redhare/exception

v0.0.2

Published

`@infra-node-kit/exception` provides exception filter and throwing methods. It combines logging module capabilities, and defines the recommended error return format.

Downloads

2

Readme

@infra-node-kit/exception

@infra-node-kit/exception provides exception filter and throwing methods. It combines logging module capabilities, and defines the recommended error return format.

Installation

yarn add '@infra-node-kit/exception'

Return format

{
  "code": 0,
  "data": null,
  "message": "ok",
  "status": 200
}

suggested error code:

enum RESPONSE_CODE {
  OK = 0,
  CUSTOM_ERROR = -1,
  VALIDATE_ERROR = -2,
  FETCH_ERROR = -3,
  AUTH_ERROR = -4,
  NOT_LOGIN = -99
}

Basic Usage

Binding filters

You must register a global-scoped filter directly from any module using the following construction. https://docs.nestjs.com/exception-filters#binding-filters

Global-scoped filters are used across the whole application, for every controller and every route handler. In terms of dependency injection, global filters registered from outside of any module (with useGlobalFilters() as in the example above) cannot inject dependencies since this is done outside the context of any module. In order to solve this issue, you can register a global-scoped filter directly from any module using the following construction:

import { UnknownExceptionFilter, HttpExceptionFilter, CustomExceptionFilter } from '@infra-node-kit/exception';
import { LoggerService } from '@infra-node-kit/logger'
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';

const INFRA_LOGNAME = 'INFRA_NODE_LOG'

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: UnknownExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: CustomExceptionFilter,
    },
    {
      provide: INFRA_LOGNAME,
      useValue: new LoggerService(),
    },
  ],
})
export class AppModule {}

WARNING: app.useGlobalFilters(new UnknownExceptionFilter(), new HttpExceptionFilter(), new CustomExceptionFilter()) This use is unsuccessful, because we have to rely on injection. You can see why in the Q & A section.

Throw error (recommend)

It is recommended to use throwError, because he can customize some reporting configurations.

import { throwError } from '@infra-node-kit/exception'

@Controller('')
export class TestController {
  @Get('/throw-error')
  throwError(): never {
    return throwError('custom error', -1, HttpStatus.NOT_FOUND)
  }
}

Throw HttpException (not recommended)

You can still use the official error throwing method, the difference between it and throwError is that you cannot customize the reporting configuration. It will be caught by HttpException exception filter. https://docs.nestjs.com/exception-filters#throwing-standard-exceptions

import { HttpStatus, HttpException } from '@nestjs/common'

@Controller('')
export class TestController {
  @Get('/httpexception')
  httpException(): never {
    throw new HttpException('httpexception', HttpStatus.BAD_REQUEST)
  }
}

Use Cases

Cases1: The first parameter provides string

throwError('custom error')

throwError('custom error', -1, HttpStatus.NOT_FOUND, {
  action: 'action',
  writeLog: true,
  logMessage: 'extralog',
})

Cases2: The first parameter provides object

throwError({ message: 'custom error' })

throwError({ message: 'custom error' }, -1, HttpStatus.NOT_FOUND, {
  action: 'action',
  writeLog: true,
  logMessage: 'extralog',
})

Cases3: The first parameter includes the logging configuration

throwError({
  message: 'custom error'
  code: -1,
  status: HttpStatus.NOT_FOUND,
  data: {
    customField: 'custom field',
  },
  action: 'action',
  writeLog: true,
  logMessage: 'logMessage',
})

Case4: Customize the message information on the log

You can use logMessage and logMessageParams, as follows:

return throwError({
  message: 'custom error'
  code: -1,
  status: HttpStatus.NOT_FOUND,
  data: {
    customField: 'custom field',
  },
  action: 'action',
  logMessage: 'prefix: %s, %s, custom',
  logMessageParams: ['param1', 'param2'],
})

The content displayed on the final log is: "message": "prefix: param1, param2, custom"

API References

import { HttpStatus } from '@nestjs/common'

export interface ILogConfig {
  /**
   * log config, custom action for easy log trace
   */
  action: string
  /**
   * log config, whether to write logs, default is true
   */
  writeLog: boolean
  /**
   * log config, some information you want to print, default is message
   */
  logMessage: string
  /**
   * log config, parameters you want to fill into logMessage %s
   */
  logMessageParams: string[]
}

export interface IStandardResponse {
  /**
   * return message
   */
  message: string
  /**
   * return code, such as RESPONSE_CODE or custom code
   */
  code: number
  /**
   * return status, use principled HTTP status codes whenever possible
   * import { HttpStatus } from '@nestjs/common'
   */
  status: HttpStatus
  /**
   * return data, some information you want to return can be put inside
   */
  data: unknown
}

export type ICustomErrorParams = Partial<IStandardResponse> & Partial<ILogConfig>

throwError(firstParams: string | ICustomErrorParams, code?: number, status?: HttpStatus, logConfig?: ILogConfig)

  • firstParams: defines the JSON response body, it can be a string or an object as described below.
  • code: defines the error code, you can use RESPONSE_CODE.
  • status: defines the HTTP status code, you can use HttpStatus.
  • logConfig: defines the logger module config.
    • action: custom action for easy log trace.
    • writeLog: whether to write logs, default is true
    • logMessage: some additional information you would like to report.
    • logMessageParams: parameters you want to fill into logMessage %s.

Logger

It is recommended to use the logger module we provide @infra-node-kit/logger.

If you still want to define your own log module, we still provide this part of the ability, you can inject a logger structure like this:

export interface ILogFields {
  action?: string
  code?: number
  status?: HttpStatus
  message?: string
  stack?: string
  logMessage?: string
}

export interface IExceptionLogger {
  warn: (fields: ILogFields) => void
  error: (fields: ILogFields) => void
}

You can implement the logic of warn and error by yourself, We pass back the parameters defined in ILogFields.

Q & A

1. Why do exception filters use dependency injection ?

Because we want to weaken the connection between packages as much as possible. Using the dependency injection pattern means that if you don't want to use the logger module we provide, you can define your own logger logic and inject it. As long as the logger method you provide meets what the exception needs internally, it will work fine.