all files / backend/ errors.js

89.47% Statements 17/19
100% Branches 6/6
80% Functions 4/5
89.47% Lines 17/19
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                                                       
'use strict'
 
class ExtendableError extends Error {
  constructor (message) {
    super(message)
    this.name = this.constructor.name
    this.message = message
    Error.captureStackTrace(this, this.constructor.name)
  }
}
 
class NotFound extends ExtendableError {
  constructor (m) {
    super(m)
    this.httpStatus = 404
  }
}
 
class BadData extends ExtendableError {
  constructor (m) {
    super(m)
    this.httpStatus = 400
  }
}
 
class Unauthorized extends ExtendableError {
  constructor (m) {
    super(m)
    this.httpStatus = 403
  }
}
 
exports.NotFound = NotFound
exports.BadData = BadData
exports.Unauthorized = Unauthorized
exports.ErrorMiddleware = function ErrorMiddleware (err, req, res, next) {
  if (err.httpStatus) {
    res.status(err.httpStatus)
  }
  if (err.name === 'MongoError' && /duplicate/.test(err.message)) {
    res.status(400)
  }
  next(err)
}