当错误信息是一个对象时,如何在javascript中创建一个新的Error
How to create a new Error in javascript when the error message is an object
我们应用中的模型层将生成一个错误数组,这些错误可能包含对象,也可能不包含对象。作为一个例子,假设有人想要POST一个thing
到我们的api,而用户提交了一个无效的有效负载,一个验证错误数组的例子可能看起来像这样:
["foo is required",
"bar must be a string",
{ orders: ["id is required", "name must be a string"]}]
注意orders
是一个对象——这是因为orders是一个对象,它有自己的属性,应该在负载中发布,我们想在该对象下命名任何验证错误,以使最终用户更清楚。
一切都很好,直到我们的框架在返回400 Bad Request之前调用new Error(validationErrors)
。
错误信息最终看起来是这样的:
{"statusCode": 400,
"error":"Bad Request",
"message":"foo is required,bar must be a string, [object Object]"}
您可以看到嵌套的订单验证对象已经丢失。
作为短期修复,我JSON.stringified
validationErrors数组,但这最终导致错误看起来像:
{"statusCode":400,
"error":"Bad Request",
"message":"['"the value of active is not allowed to be undefined'",'"the value of name is not allowed to be undefined'",'"the value of team is not allowed to be undefined'",'"the value of startDate is not allowed to be undefined'",'"the value of endDate is not allowed to be undefined'",{'"location'":['"the value of name is not allowed to be undefined'",'"the value of latitude is not allowed to be undefined'",'"the value of longitude is not allowed to be undefined'"]}]"}
这个问题有更好的解决办法吗?
给定输入:
var errors = [
"foo is required",
"bar must be a string",
{ orders: ["id is required", "name must be a string"]}
];
你可以把它转换成这样的输出:
[
"foo is required",
"bar must be a string",
"orders: id is required",
"orders: name must be a string"
]
由于您没有提供预期的输出,所以我只是编了一个。
代码:
errs.reduce(function(output, current){
if (typeof current == 'object') {
var key = Object.keys(current)[0];
output = output.concat(current[key].map(function(err) {
return key + ': ' + err;
}));
}
else {
output.push(current);
}
return output;
}, []);
解释:
加勒比海盗。Reduce接受两个参数:一个是对数组中的每个元素调用的函数,另一个是收集第一个函数输出的初始值。
加勒比海盗。Map接受一个形参:一个转换上下文数组中每个元素的函数。
我们从错误开始。reduce,初始值为[]
。我们将查看输入数组中的每个错误。如果是字符串,则将其压入输出数组。如果它是一个对象,那么我们通过跟踪key
(object .keys()[0])将{orders: ['error one', 'error two']}
转换为['orders: error one', 'orders: error two']
,并使用map来转换。
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 从javascript创建一个列表
- Kendo:我该如何在树视图中创建一个递归的hieiarchy
- 从html创建一个指令,该指令按类名应用函数
- 如何为jQuery屏蔽输入插件创建一个允许字母数字、空格和重音字符的掩码
- 我想在AngularJS应用程序中创建一个输入数字框,用户不应该在该框上键入十进制数字.(一个整数输入框)
- 是否可以使用JavaScript/AAJAX在客户端创建一个文件
- 如何创建一个“;表单弹出框“;在chrome中右键单击时位于突出显示的单词上方
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 创建一个循环来简化HTML和CSS代码
- 在javascript中的xml中创建一个链接
- 尝试创建一个具有z-index的堆叠菜单'使用HTML5/CSS3/JS
- 创建一个方法,通过一个窗口进行迭代并获取Titanium中的所有控件
- 用javascript创建一个看起来正常分布的模式
- 如何创建一个方法来验证数组的范围
- 在量角器中创建一个.txt错误输出文件是手动的,而不是控制台错误
- 动态创建一个javascript/jquery多级数组
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- 为网站表单创建一个专业的日历
- 如何创建一个具有固定左右列和水平滚动的表