BETTERZON-38: Added error handler, preparation for DB accessing

This commit is contained in:
2020-11-25 00:38:16 +01:00
parent 5b04b810dc
commit 6b8acdab46
9 changed files with 1700 additions and 57 deletions
+13
View File
@@ -0,0 +1,13 @@
export default class HttpException extends Error {
statusCode: number;
message: string;
error: string | null;
constructor(statusCode: number, message: string, error?: string) {
super(message);
this.statusCode = statusCode;
this.message = message;
this.error = error || null;
}
}
+5
View File
@@ -7,6 +7,8 @@ import express from "express";
import cors from "cors";
import helmet from "helmet";
import { productsRouter } from "./products/products.router";
import { errorHandler } from "./middleware/error.middleware";
import {notFoundHandler} from "./middleware/notFound.middleware";
dotenv.config();
@@ -33,6 +35,9 @@ app.use(cors());
app.use(express.json());
app.use("/products", productsRouter);
app.use(errorHandler);
app.use(notFoundHandler);
/**
* Server Activation
@@ -0,0 +1,15 @@
import HttpException from "../common/http-exception";
import { Request, Response, NextFunction } from "express";
export const errorHandler = (
error: HttpException,
request: Request,
response: Response,
next: NextFunction
) => {
const status = error.statusCode || 500;
const message =
error.message || "It's not you. It's us. We are having some problems.";
response.status(status).send(message);
};
@@ -0,0 +1,12 @@
import { Request, Response, NextFunction } from "express";
export const notFoundHandler = (
request: Request,
response: Response,
next: NextFunction
) => {
const message = "Resource not found";
response.status(404).send(message);
};