[Express] Add error handling middleware for express

Express app:

import cors from 'cors';
import express, { Application } from 'express';
import routes from './routes';
import * as middlewares from './middleware';

const app: Application = express();

app.use(cors());
app.use(express.json());
app.use(middlewares.logger);
app.use('/api', routes);
// add error handling middleware to catch errors
app.use(middlewares.unknownEndPoint);
app.use(middlewares.errorHandler);

export default app;

 

Middlewares:

import { Request, Response, NextFunction } from 'express';
import { error as logError } from './logger';

function logger(req: Request, _res: Response, next: NextFunction): void {
  if (process.env.NODE_ENV !== 'test') {
    console.info(`${req.method} ${req.url}`);
  }
  next();
}

function unknownEndPoint(_req: Request, res: Response, _next: NextFunction): void {
  res.status(404).send({ error: 'Unknown endpoint' });
}

function errorHandler(e: Error, _req: Request, res: Response, next: NextFunction) {
  logError(e.message);
  switch (e.name) {
    case 'SequelizeForeignKeyConstraintError':
      return res.status(500).json({ error: 'Station Id not exists in the database' });
    case 'Missing data':
      return res.status(400).json({ error: e.message });
    case 'Invalid data':
      return res.status(400).json({ error: e.message });
    case 'Unreachable data':
      return res.status(404).json({ error: e.message });
    default:
      return next(e);
  }
}

export {
  logger,
  unknownEndPoint,
  errorHandler,
};

 

posted @ 2023-02-05 01:07  Zhentiw  阅读(24)  评论(0编辑  收藏  举报