只有当它是 Lambda 代理时,您才能自定义异常标头,使用 API Gateway(x-amzn-errortype 标头),在任何其他情况下,您需要解析异常消息以获取您的自定义异常,这里是一个示例我如何管理 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 服务能够完全自定义异常而没有太多麻烦。
问候!