06 - RESPONSE NORMALIZATION STRATEGIES Flashcards
creating a currentUser route handler
export { router as currentUserrouter }
app.use(currrentUserRouter);
validating requests with express-validator
import body, validationResult
how to handle and structure errors
consistent structure for validation and other type of errors in a middleware
error handler
import { Request, Response, NextFunction } from “response”;
export const errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
};
creating a RequestValidationError class
import { ValidationError } from “express-validator”;
export class RequestValidationError extends Error {
constructor(public errors: ValidationError[ ] ) {
super( );
// only when extending a build in class Object.setPrototypeOf(this, RequestValidationError.prototype); } }
database connection error class
export class DatabaseConnectionError extends Error {
reason = “Error connecting to database”;
constructor( ) { super( ); // only when extending a build in class Object.setPrototypeOf(this, DatabaseConnectionError.prototype); } }
throwing custom error classes
throw new RequestValidationError(errors.array( ));
throw new DatabaseConnectionError( );
common response error structure
{
errors: {
message: string, field?: string
}[ ]
}
add serializeErrors method to each error class
serializeErrors( ) {
return [
{ message: “reason” }
];
}
}
serialize method in RequestValidationError class
serializeErrors( ) {
return this.errors.map(err => {
return { message: err.msg, field: err.param }
});
}
create CustomError Abstract class
export abstract class CustomError extends Error {
abstract statusCode: number;
constructor( ) { super( ); Object.setPrototypeOf(this, CustomError.prototype); } abstract serializeErrors( ): { message: string; field?: string } [ ] }
using CustomError in errorHandler middleware
if (err instanceOf CustomError) {
return status(err.statusCode).send({ errors: err.serializeErrors( ) });
}
create a route not found custom error
import { CustomError } from “custom-error”;
export class NotFoundError extends CustomError {
statusCode = 404;
constructor( ) { super("Route not found"); Object.setPrototypeOf(this, NotFoundError.prototype); } serializeErrors( ) { return [ { message: "Not Found" } ] } }
app.get(“*”, ( ) => {
throw new NotFoundError( )
});
install express-async-errors
app.all(“*”, async (req, res, next ) => {
next ( new NotFoundError( ));
});