如何从 Cognito 获取编程错误代码?
How do I get programmatic error codes from Cognito?
我正在使用 Cognito Javscript SDK,并且我创建了一个表单,用户可以在其中注册帐户。如果出于某种原因服务器端验证失败,则响应如下所示:
{
"__type":"InvalidParameterException",
"message":"4 validation errors detected: Value at 'password' failed to satisfy constraint: Member must have length greater than or equal to 6; Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value at 'username' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+"
}
此响应的问题是我无法提供良好的用户反馈,因为我必须解析响应以确定需要修复哪些字段。有没有办法以更适合以编程方式处理的格式恢复错误?
目前最好的方法是通过删除 'value at' 之后的子字符串以编程方式获取值。
我还没有任何图书馆的例子可以帮助做到这一点,但这是很好的反馈。
以防万一以后有人遇到这个问题,答案是使用 response.code:
this.cognitoUser.forgotPassword({
onSuccess: (data) => {
},
onFailure: (data) => {
console.log(data)
/*
{
"__type":"InvalidParameterException",
"message":"4 validation errors etc"
}
*/
console.log(data.code)
/*
"InvalidParameterException"
*/
}
})
您必须先 json 字符串化,然后 json 解析对象以获取值。
尝试以下示例代码 -
var errorObj = JSON.parse(JSON.stringify(data));
console.log(errorObj.statusCode);
我正在使用 Cognito Javscript SDK,并且我创建了一个表单,用户可以在其中注册帐户。如果出于某种原因服务器端验证失败,则响应如下所示:
{
"__type":"InvalidParameterException",
"message":"4 validation errors detected: Value at 'password' failed to satisfy constraint: Member must have length greater than or equal to 6; Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value at 'username' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+"
}
此响应的问题是我无法提供良好的用户反馈,因为我必须解析响应以确定需要修复哪些字段。有没有办法以更适合以编程方式处理的格式恢复错误?
目前最好的方法是通过删除 'value at' 之后的子字符串以编程方式获取值。
我还没有任何图书馆的例子可以帮助做到这一点,但这是很好的反馈。
以防万一以后有人遇到这个问题,答案是使用 response.code:
this.cognitoUser.forgotPassword({
onSuccess: (data) => {
},
onFailure: (data) => {
console.log(data)
/*
{
"__type":"InvalidParameterException",
"message":"4 validation errors etc"
}
*/
console.log(data.code)
/*
"InvalidParameterException"
*/
}
})
您必须先 json 字符串化,然后 json 解析对象以获取值。
尝试以下示例代码 -
var errorObj = JSON.parse(JSON.stringify(data));
console.log(errorObj.statusCode);