gpt4 book ai didi

node.js - 自定义异常名称而不是 UserLambdaValidationException

转载 作者:太空宇宙 更新时间:2023-11-03 22:39:57 25 4
gpt4 key购买 nike

我使用 Cognito 的预注册触发器来验证用户注册。如果某些验证失败,函数会响应自定义错误。客户端仅收到 UserLambdaValidationException 作为 ErrorCode

有没有办法接收自定义错误名称?

当前使用示例:

exports.handler = function(event, context, callback) {                
function AccountAlreadyExistsError(message) {
this.name = "AccountAlreadyExistsError";
this.message = message;
}
AccountAlreadyExistsError.prototype = new Error();

const error = new AccountAlreadyExistsError("Account is in use!");
callback(error);
};

我想在我们的客户端中获取 AccountAlreadyExistsError 而不是 UserLambdaValidationException

最佳答案

仅当它是 Lambda 代理且具有 API 网关(x-amzn-errortype header )时,您才可以自定义异常 header ,在任何其他情况下,您都需要解析异常消息以获取自定义异常,这里是一个示例我如何管理 Cognito lambda 触发器的异常,这只是为了向您展示这个想法:

/*
Lambda Code, could be in a Lambda layer
*/
const EXCEPTION_TYPE_DELIMITER = "etype"
const EXCEPTION_MESSAGE_DELIMITER = "emsg";

const beTagged = (tag, txt) => {
return "<" + tag + ">" + txt + "</" + tag + ">";
};

class UserNotAllowedException extends Error {
constructor (message) {
super(beTagged(EXCEPTION_MESSAGE_DELIMITER, message))
Error.captureStackTrace(this, this.constructor);
this.name = beTagged(EXCEPTION_TYPE_DELIMITER, this.constructor.name);
}
}

exports.handler = async (event, context, callback) => {
// Your logic, etc..
throw new UserNotAllowedException("You are blocked :(");
}

这是解析器

/*
Client Code
*/
const EXCEPTION_TYPE_DELIMITER_REGEX = /<etype>(.*?)<\/etype>/g;
const EXCEPTION_TYPE_UNTAG_REGEX = /<\/?etype>/g;
const EXCEPTION_MESSAGE_DELIMITER_REGEX = /<emsg>(.*?)<\/emsg>/g;
const EXCEPTION_MESSAGE_UNTAG_REGEX = /<\/?emsg>/g;

const untag = (txt, delimiterRegex, untagRegex) => {
return txt.match(delimiterRegex).map(etype => {
return etype.replace(untagRegex,"");
})[0];
};

const resolveException = (exceptionMessage) => {
const exceptionType = untag(exceptionMessage, EXCEPTION_TYPE_DELIMITER_REGEX, EXCEPTION_TYPE_UNTAG_REGEX);
const exceptionMessage = untag(exceptionMessage, EXCEPTION_MESSAGE_DELIMITER_REGEX, EXCEPTION_MESSAGE_UNTAG_REGEX);
// Your logic to determine what exception is the exceptionType
return new YourResolvedException(exceptionMessage);
};

try {
// This guy should throw the exception
return await Auth.signUp(params);
} catch (e) {
// Expected message from Cognito Lambda Trigger
// PreSignUp failed with error <etype>UserNotAllowedException</etype>: <emsg>You are blocked :(</emsg>.
// For example, here your custom exception resolver
throw resolveException(e.message);
}

这可以通过一千种方式完成,但对我们来说最好的事情是 AWS 服务能够完全自定义异常,而无需那么多麻烦。

问候!

关于node.js - 自定义异常名称而不是 UserLambdaValidationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47469160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com