当错误信息是一个对象时,如何在javascript中创建一个新的Error

How to create a new Error in javascript when the error message is an object

本文关键字:创建 一个 Error javascript 一个对象 信息 错误      更新时间:2023-09-26

我们应用中的模型层将生成一个错误数组,这些错误可能包含对象,也可能不包含对象。作为一个例子,假设有人想要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来转换。