summaryrefslogtreecommitdiff
path: root/goodgame/src/utils/errorHandlers.js
blob: 4c7fe9f5338a0c875b5c27804f3c28860ef89fee (plain)
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
/*
  Catch Errors Handler

  With async/await, you need some way to catch errors
  Instead of using try{} catch(e) {} in each controller, we wrap the function in
  catchErrors(), catch any errors they throw, and pass it along to our express middleware with
  next()
*/

exports.catchErrors = fn => (req, res, next) => {
  return fn(req, res, next).catch(next);
};

/*
  Not Found Error Handler

  If we hit a route that is not found, we mark it as 404 and pass it along to the next error handler
  to display
*/
exports.notFound = (req, res, next) => {
  const err = new Error('This route does not exists');
  err.status = 404;
  next(err);
};

/*
  MongoDB Validation Error Handler

  Detect if there are mongodb validation errors that we can nicely show via flash messages
*/

exports.flashValidationErrors = (err, req, res, next) => {
  if (!err) {
    return next();
  }

  return res.status(err.status || 400).json({
    ok: false,
    message: 'There was an internal error',
    errors: err.message,
  });
};

/*
  Production Error Handler

  No stacktraces are leaked to user
*/
/* istanbul ignore next */
exports.productionErrors = (err, req, res) => {
  res.status(err.status || 500).json('error', {
    ok: false,
    message: err.message,
    error: {},
  });
};