node.js - 扩展运算符似乎没有复制完整对象
问题描述
我正在尝试实现快速错误处理中间件。它正在工作,但我不明白为什么我必须在复制error.message
到. 扩展运算符是否没有从 复制所有属性?当我检查 err 对象时,我什至看不到消息或堆栈属性。另外,为什么它能够在 if 块中创建错误消息之前记录错误消息。err.message
err
error
err
这就是我扩展错误的方式
// 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)
}
}
解决方案
发生这种情况是因为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
推荐阅读
- r - 绘制一年中 4 个季度(Q1、Q2、Q3 和 Q4)的 Dataframe 中两列之间的差异的问题
- python - 如何使用python从距离矩阵制作OD对字典?
- core-data - NSPersistentCloudKitContainer 不在后台同步
- html - Angular & Bootstrap:数据切换不适用于 Angular
- javascript - scrollY 和 scrollTop 的区别
- c++ - 如何在 C++ 中声明和使用二维指针数组
- c++ - 调试器:如何在构造函数中获取类名的地址
- tensorflow - 使用 MirroredStrategy() 卡住模型
- java - 将数据从firebase添加到android中的listview
- javascript - 我如何在 Material-ui 中实现下拉标题?