我正在使用 NodeJS 和 Express 开发一个 RESTful API。
我注意到传入的请求有时缺少一些预期的变量,这会导致程序崩溃,说它无法将变量的值设置为一个'undefined'
值——因为请求没有到达值。
示例:
应用程序需要 variableY,但正在发送 variableX:
formData: { variableX: 'valueX' }
该程序期望接收变量Y,代码如下:
const checkVariables = Joi.validate({
variableY: req.body.variableY,
}, schema);
应用程序崩溃并出现以下错误:
TypeError: Cannot read property 'variableY' of undefined
我想了一些方法来处理这个问题,包括在应用程序启动时声明变量并一起使用它们,使用try-catch
.
另一种方法是使用if-else
, if-chaining
, or case-switch
,但正如您所理解的那样,我当然正在寻找实现这一目标的最干净的方法。
有任何想法吗?
谢谢你。
** 编辑 **
仅使用对象进行并设法实现结果。一旦试图到达它的任何内部字段,无论如何都会抛出错误,例如:
if(req.body.variableY == undefined){console.log('The expected variable is undefined');} //true
当验证处理“未定义”对象内的字段时:
if(req.body.variableY.dataId == undefined){console.log('The expected variable is undefined');} //crashes
再次引发以下错误:
TypeError: Cannot read property 'variableX' of undefined
在做了一些更多的挖掘之后,发现了这个 Stackoverflow 线程:
如何检查对象属性是否存在与持有属性名称的变量?
尝试使用 hasOwnProperty,但抛出了相同类型的错误:
TypeError: Cannot read property 'hasOwnProperty' of undefined
尝试使用包装变量声明try-catch
,仍然没有工作:
try{
var variableX = req.body.variableX
var variableXDataId = req.body.variableX.dataId
}
catch(e){
res.status(400).send('Wrong request error: Please check your request variables and try again');
}
因为这是一个非常基本的验证,应该由大多数 RESTful API 解决(验证您在请求中获得了预期的传入变量,因此程序不会因无法处理的错误而崩溃 - 常见的此类问题的解决方案(预期/意外请求验证)?
谢谢你。