首页 > 解决方案 > 扩展运算符似乎没有复制完整对象

问题描述

我正在尝试实现快速错误处理中间件。它正在工作,但我不明白为什么我必须在复制error.message到. 扩展运算符是否没有从 复制所有属性?当我检查 err 对象时,我什至看不到消息或堆栈属性。另外,为什么它能够在 if 块中创建错误消息之前记录错误消息。err.messageerrerrorerr

这就是我扩展错误的方式

// src/utils/errorResponse.js

class ErrorResponse extends Error {
  constructor(message, statusCode) {
    super(message)
    this.statusCode = statusCode
  }
}
module.exports = ErrorResponse

自定义错误处理程序中间件

// src/middleware/error.js

const ErrorResponse = require('../utils/errorResponse')

const errorHandler = (err, req, res, next) => {
  let error = { ...err } 
  console.log({ error.message }) // undefined
  error.message = err.message
  console.log({ error.message }) // `Resource not found with id of ${err.value}`

  // Log to console for dev
  // console.log(error.stack)

  // Mongoose bad ObjectId
  if (err.name === 'CastError') {
    const message = `Resource not found with id of ${err.value}`
    error = new ErrorResponse(message, 404)
  } else {
    console.log(error.name)
  }

  res.status(error.statusCode || 500).json({
    success: false,
    error: error.message || 'Server Error',
  })
}

module.exports = errorHandler

我通过使用错误的 ObjectID 发出获取请求来触发错误

// src/controllers/bootcamp.js

const Bootcamp = require('../models/Bootcamp')

...

// @desc Get single bootcamp
// @route GET /api/v1/bootcamps/:id
// @access Public
exports.getBootcamp = async (req, res, next) => {
  try {
    const bootcamp = await Bootcamp.findById(req.params.id)
    if (!bootcamp) {
      return next(err)
    }
    res.status(200).json({ success: true, data: bootcamp })
  } catch (err) {
    next(err)
  }
}

标签: node.jsexpressmiddleware

解决方案


发生这种情况是因为err您获得的参数是错误类型对象,并且消息键存在于错误对象的原型中,并且传播运算符浅拷贝对象的键(不包括原型键)

来自 mdn 的扩展运算符声明 -

ECMAScript 提案 (ES2018) 的 Rest/Spread Properties 向对象文字添加了扩展属性。它将自己的可枚举属性从提供的对象复制到新对象上。

(excluding prototype)现在可以使用比 Object.assign() 更短的语法对对象进行浅克隆或合并。

以供参考 -

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


推荐阅读