提交 ec48f19c96c4277bf8d80b041561cfd99e73d757

作者 Nick Baugh
1 个父辈 c06c1c50

added error handler

正在显示 1 个修改的文件 包含 87 行增加0 行删除
  1 +
  2 +// # error handler
  3 +
  4 +var _ = require('underscore')
  5 +var util = require('util')
  6 +
  7 +exports = module.exports = function(logger, settings) {
  8 +
  9 + return function(err, req, res, next) {
  10 +
  11 + // set default error status code
  12 + res.statusCode = (_.isNumber(err.status)) ? err.status : 500
  13 +
  14 + if (!_.isString(err.message))
  15 + err.message = 'An unknown error has occured, please try again'
  16 +
  17 + if (_.isObject(err) && _.isNumber(err.code) && err.code === 11000)
  18 + err.message = 'Duplicate document already exists in database, try making a more unique value'
  19 +
  20 + // if we pass an error object, then we want to simply return the message...
  21 + // if we pass an object, then we want to do a stack trace, and then return the object + stack
  22 + var error = {}
  23 +
  24 + // set error type
  25 + error.type = _.isString(err.param) ? 'invalid_request_error' : 'api_error'
  26 +
  27 + if (error.type === 'invalid_request_error' && res.statusCode === 500)
  28 + res.statusCode = 400
  29 +
  30 + // set error message and stack trace
  31 + if (util.isError(err)) {
  32 + error.message = err.message
  33 + } else {
  34 + _.extend(error, err)
  35 + }
  36 +
  37 + // set status code for BadRequestError
  38 + if (_.isString(error.name) && error.name === 'BadRequestError') {
  39 + error.type = 'invalid_request_error'
  40 + res.statusCode = 400
  41 + delete error.name
  42 + }
  43 +
  44 + if (settings.showStack)
  45 + error.stack = _.isUndefined(err.stack) ? new Error(err.message).stack : err.stack
  46 +
  47 + // set error level
  48 + var level = (res.statusCode < 500) ? 'warn' : 'error'
  49 + logger[level](error)
  50 +
  51 + // set error back to warning if it was warn
  52 + // logger level type = "warn"
  53 + // req.flash messages type = "warning"
  54 + if (level === 'warn')
  55 + level = 'warning'
  56 +
  57 + // if we have a mongoose validation err
  58 + // then we know to output all the errors
  59 + if (_.isObject(error.errors) && !_.isEmpty(error.errors)) {
  60 + var messages = []
  61 + _.each(error.errors, function(errMsg) {
  62 + if (_.isString(errMsg.message))
  63 + messages.push(errMsg.message)
  64 + })
  65 + if (!_.isEmpty(messages))
  66 + error.message = messages.join(' ')
  67 + }
  68 +
  69 + res.format({
  70 + text: function() {
  71 + res.send(error.message)
  72 + },
  73 + html: function() {
  74 + req.flash(level, error.message)
  75 + res.redirect('back')
  76 + },
  77 + json: function() {
  78 + res.json({ error: error })
  79 + }
  80 + })
  81 +
  82 + }
  83 +
  84 +}
  85 +
  86 +exports['@singleton'] = true
  87 +exports['@require'] = [ 'logger', 'settings' ]
... ...
注册登录 后发表评论