Skip to content

Instantly share code, notes, and snippets.

@alexpermiakov
Last active December 15, 2018 17:03
Show Gist options
  • Save alexpermiakov/53c11b8f4abf255aa75078a7eec9e947 to your computer and use it in GitHub Desktop.
Save alexpermiakov/53c11b8f4abf255aa75078a7eec9e947 to your computer and use it in GitHub Desktop.
ErrorHandlers middleware
import { Request, Response, NextFunction, Router } from "express";
import { HTTPClientError, HTTP404Error } from "../utils/httpErrors";
const handle404Error = (router: Router) => {
router.use((req: Request, res: Response) => {
throw new HTTP404Error("Method not found.");
});
};
const handleClientErrors = (router: Router) => {
router.use((err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof HTTPClientError) {
console.error(err);
res.status(err.status).send(err.message);
} else {
next(err);
}
});
};
const handleServerErrors = (router: Router) => {
router.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err);
if (process.env.NODE_ENV === "production") {
res.status(500).send("Internal Server Error");
} else {
res.status(500).send(err.stack);
}
});
};
export default [handle404Error, handleClientErrors, handleServerErrors];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment