@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
Keywords
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 astring
or anobject
as described below.code
: defines the error code, you can useRESPONSE_CODE
.status
: defines the HTTP status code, you can useHttpStatus
.logConfig
: defines the logger module config.action
: custom action for easy log trace.writeLog
: whether to write logs, default is truelogMessage
: 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.