File size: 1,700 Bytes
e8c33fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const { env } = require('../configs/env');
const { logError } = require('../utils/errorLogger');

const HTTP_CODE_MAP = {
  400: 'BAD_REQUEST',
  401: 'UNAUTHORIZED',
  403: 'FORBIDDEN',
  404: 'NOT_FOUND',
  409: 'CONFLICT',
  413: 'PAYLOAD_TOO_LARGE',
  422: 'UNPROCESSABLE_ENTITY',
  429: 'RATE_LIMIT_EXCEEDED',
  503: 'SERVICE_UNAVAILABLE',
};

const getCode = (statusCode) =>
  HTTP_CODE_MAP[statusCode] || (statusCode >= 500 ? 'INTERNAL_SERVER_ERROR' : 'REQUEST_FAILED');

const errorHandler = (err, req, res, _next) => {
  let statusCode = err.statusCode || err.status || (res.statusCode === 200 ? 500 : res.statusCode);
  let message = err.message || 'Something went wrong';

  if (err?.name === 'MulterError') {
    statusCode = 400;
    if (err.code === 'LIMIT_FILE_SIZE') {
      message = 'File is too large. Please check the maximum upload size for this action.';
    } else if (err.code === 'LIMIT_UNEXPECTED_FILE') {
      const field = String(err.field || '').trim();
      message = field
        ? `Unexpected upload field: ${field}. Please upload the file using the correct form field.`
        : 'Unexpected upload field. Please upload the file using the correct form field.';
    }
  }

  const code = getCode(statusCode);

  if (statusCode >= 500) {
    logError(err, { req, statusCode, code });
    if (env.isProduction) {
      message = 'An internal error occurred. Please try again later.';
    }
  }

  res.status(statusCode).json({ success: false, message, code });
};

const notFound = (req, res) => {
  res.status(404).json({
    success: false,
    message: `Not found: ${req.originalUrl}`,
    code: 'NOT_FOUND',
  });
};

module.exports = { errorHandler, notFound };