@nestling/errors
v1.5.1
Published
Error Handling for NestJS
Readme
Nestling errors module
This module tries to make it easier to handle errors and send back meaningful information to the client.
It consist of a way to define your own messages for common errors and also intercept third party errors and normalize them into a common response.
Application level error messages
As a convention you can suffix your files with .errors.ts and keep the errors close to where they are used.
users.errors.ts
import { HttpStatus } from '@nestjs/common'
import { IErrorMessages } from '../errors/ErrorMessage'
// Optional: to typecheck interpolation vars
export interface UserEmailAlreadyExistError {
email: string
}
export const userErrors: IErrorMessages = {
type: 'user',
errors: [
{
code: 'credentialsInvalid',
statusCode: HttpStatus.BAD_REQUEST,
message: 'Invalid Credentials.'
},
{
code: 'emailAlreadyExist',
statusCode: HttpStatus.BAD_REQUEST,
message: 'Email {email} already exist.'
}
...etc
]
}In order to use the error messages they must be registered first:
ErrorMessage.addErrorMessages(userErrors)The error messages can be used like this:
import { ErrorMessage } from '@nestling/errors'
throw new ErrorMessage('user:credentialsInvalid')
throw new ErrorMessage<UserEmailAlreadyExist>('user:emailAlreadyExists', {
email: '[email protected]'
})Setup
In able to filter for errors the exception filter must be added to the app's components:
import { HttpExceptionFilter } from '@nestling/errors'
@Module({
components: [
HttpExceptionFilter
]
})
export class ApplicationModule implements NestModule {
configure (consumer: MiddlewaresConsumer): void {
}
}
The filter will intercept all exceptions thrown, if an unknown exception is encountered a 500 error will be returned.
Adding extra error handlers
To register a new error handler use:
import ValidationError = require('ajv')
import { HttpStatus } from '@nestjs/common'
import { IErrorMessage } from '../../ErrorMessage'
export const validationErrorHandler = {
type: ValidationError,
handler: (exception): IErrorMessage => {
return {
code: `validation:${exception.errors[0].keyword}`,
message: exception.errors[0].message,
statusCode: HttpStatus.BAD_REQUEST
}
}
}
HttpExceptionFilter.addExceptionHandler(validationErrorHandler)The type will be used to do an instance of check, the handler normalizes the error message into a common format.
Error Response Handler
To override the default response handler use:
HttpExceptionFilter.setErrorResponseHandler((error, response) => {
response.setHeader(`x-error-code`, error.code)
response.setHeader(`x-error-message`, error.message)
response.setHeader(`x-error-statusCode`, error.statusCode)
response
.status(error.statusCode)
.json(error)
console.error(error)
})