express-customize-errors
v1.0.14
Published
A light weight node express package that serves as a centralized error management system. This Package helps you serialize all errors in your express app before sending them back to the client, comes with built-in support for typescript
Downloads
7
Readme
express-customize-errors
A light weight node express package that serves as a centralized error management system. This Package helps you serialize all errors in your express app before sending them back to the client, comes with built-in support for typescript.
Installation
npm install express-customize-errors
Basic Usage
Here is a simple example using typescript, to help you get the gist.
import express, { Request, Response, NextFunction } from 'express';
import { NotFoundError, ErrorHandler } from 'express-customize-errors';
const port = process.env.PORT || 3000;
const app = express();
app.all("*", ( req:Request,res:Response, next:NextFunction )=>{
return next(new NotFoundError('Route Not Found')); // Expected output: { "errors": [{ "message": "Route not found" }] }
});
app.use(ErrorHandler);
app.listen(port, () =>{
console.log(`LISTENING ON PORT ${port}`);
});
You can also create your own custom errors of by levelaging the custom error class as demonstrated in the example below:
Step 1
Inside your project create an errors folder and then create a file with a name of your choice where you are going to define your custom error signature. preferably use the actual name of the error.
Eg : /errors/database-connection-error.ts
Step 2
Import the CustomError class
import CustomError from 'express-customize-errors';
Define error signature as follows:
export class DatabaseConnectionError extends CustomError {
statusCode = 500;
constructor(public message: string ) {
super(message);
Object.setPrototypeOf(this, DatabaseConnectionError.prototype);
}
serializeErrors() {
return [{ message: this.message }];
}
};
Once done now you can import this newly created error and use it across your entire application Let's use it inside app.ts file
import express, { Request, Response, NextFunction } from 'express';
// import in Errorhandler middleware & NotFoundError
import { NotFoundError, ErrorHandler } from 'express-customize-errors';
import { DatabaseConnectionError } from './errors/database-connection-error';
import mongoose from 'mongoose';
const port = process.env.PORT || 3000;
const app = express();
app.all("*", ( req:Request,res:Response, next:NextFunction )=>{
// pass a new extended custom error into the express nextFunction
return next(new NotFoundError('Route Not Found')); // Expected Output: { "errors": [{ "message": "Route not found" }] }
});
const connectDatabase = async () => {
try{
await mongoose.connect(process.env.MONGO_URI as string);
console.log('CONNECTED TO DATABASE');
}catch(err){
return next({ err }); // Expected Output: { errors:[ { message: 'Internal Server Error' }] }
throw new DatabaseConnectionError('Could not connect to DB'); // Expected Output: { errors:[ {message: 'Could not connect to DB'}] }
}
};
// consume Error handler
app.use(ErrorHandler);
app.listen(port, () =>{
console.log(`LISTENING ON PORT ${port}`);
});
connectDatabase();
Asyncronous Codes
If you wish to use custom errors inside an async fuction be sure to install and import express-async-errors package
npm install express-async-errors
Then simply import it in your server file eg: app.ts
import 'express-async-errors';
Usage with express-validator
npm install express-validator express-customize-errors
Create an errors folder in your root directory and inside this errors folder create a file and paste in the code below
import { CustomError, ExpressValidationError} from 'express-customize-errors';
export class RequestValidationError extends CustomError {
statusCode= 400;
constructor(private errors:ExpressValidationError[]){
super('invalid request params');
Object.setPrototypeOf(this, RequestValidationError.prototype);
};
serializeErrors(){
console.log('this is errors', this.errors);
return this.errors.map(err => {
return{ message: err.msg, field: err.path };
})
};
}
Now apply your RequestValidationError in application routes and services
import express, { Request, Response, NextFunction } from 'express';
import { body, validationResult } from 'express-validator';
import { RequestValidationError } from '../errors/requestValidationError';
import { convertToExpressValidationError } from 'express-customize-errors';
const router = express.Router({ mergeParams: true });
router.post('/api/auth/signup', [
body('email')
.isEmail()
.withMessage('Invalid Email'),
body('password')
.trim()
.isLength({ min: 4, max: 15 })
.withMessage('Password must contain at least 4-15 chars')
], (req: Request, res: Response, next: NextFunction) => {
console.log('req.body..', req.body);
const errors = validationResult(req);
if (!errors.isEmpty()) {
const expressErrors = convertToExpressValidationError(errors.array());
return next(new RequestValidationError(expressErrors));
// Expected output:
// {
// "errors": [
// {
// "message": "Invalid Email",
// "field": "email"
// },
// {
// "message": "Password must contain atleast 4-15 chars",
// "field": "password"
// }
// ]
// }
}
console.log('creating a user...');
return;
});
export { router as authRoutes };
CustomError constructor
Parameters and their respective types and requirements
| Name | Required | Type |
|---------------------------|-------------------------------|-------------------------------------------------------------------|
| message | true | String |
| field | false | String |
| serializeErrors | true | function serializeErrors(): { message: string; field?: string }[];|
| | | |
Built in Custom Errors Usage
| Name | StatusCode | Customizable Message | |---------------------------|-------------------------------|------------------------------------------------------------------| | BadRequestError | 400 | Eg: "Bad Request Error" | | NotFoundError | 404 | Eg: "Not Found" | | NotAuthorizedError | 401 | Eg: "Not Authorized " | | RequestValidationError | 403 | Eg: "Request Validation Failed" | |