aboutsummaryrefslogtreecommitdiffstats
path: root/backend/src/middleware/error.middleware.js
blob: e037cff79dd6b60fc959e9871a1fe8c8e761575e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const env = require('../config/env');

/**
 * Not found error handler middleware
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next function
 */
const notFound = (req, res, next) => {
  const error = new Error(`Not Found - ${req.originalUrl}`);
  res.status(404);
  next(error);
};

/**
 * General error handler middleware
 * @param {Error} err - Error object
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next function
 */
const errorHandler = (err, req, res, next) => {
  // Log the error
  console.error(err.stack);
  
  // Set status code
  const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
  
  // Send response
  res.status(statusCode).json({
    message: err.message,
    stack: env.NODE_ENV === 'production' ? '🥞' : err.stack,
    error: env.NODE_ENV === 'development' ? err : {}
  });
};

module.exports = {
  notFound,
  errorHandler
};