Amplify Gen 2 Lambda查询如何返回自定义errorType而非Lambda:Unhandled
解决Amplify Gen 2自定义Lambda查询返回自定义errorType的问题
要让前端拿到自定义的errorType,核心是让Lambda返回的错误对象符合Amplify Data能识别的格式,不能直接用普通Error类或简单抛错,以下是具体实现方案:
1. 定义带errorType的自定义错误类(推荐)
创建继承自Error的自定义类,确保errorType属性能被正确序列化:
class CustomAppError extends Error { errorType: string; constructor(message: string, errorType: string) { super(message); this.errorType = errorType; // 修复TypeScript原型链问题,避免序列化丢失属性 Object.setPrototypeOf(this, CustomAppError.prototype); } // 自定义序列化逻辑,确保errorType被包含在返回结果中 toJSON() { return { message: this.message, errorType: this.errorType, stack: this.stack }; } }
2. 在Lambda处理器中使用自定义错误
方式一:抛出自定义错误
在异步处理器中直接抛出CustomAppError,Lambda会自动序列化这个错误并传递给Amplify:
export const handler = async (event: any) => { // 模拟业务错误场景 if (!event.arguments.userId) { throw new CustomAppError("用户ID不能为空", "ValidationError"); } // 正常业务逻辑,返回预期数据类型 const result = await getCustomData(event.arguments.userId); return result; };
方式二:使用callback返回错误
如果使用传统callback模式,直接传递包含errorType的对象(不要传普通Error实例):
export const handler = async (event: any, context: any, callback: any) => { try { if (!event.arguments.userId) { const customError = { message: "用户ID不能为空", errorType: "ValidationError" }; callback(customError, null); return; } const result = await getCustomData(event.arguments.userId); callback(null, result); } catch (err) { // 捕获其他异常并转为自定义错误类型 callback({ message: err instanceof Error ? err.message : "未知错误", errorType: "ServerError" }, null); } };
关键注意事项
- 避免使用普通
Error类:Lambda默认序列化普通Error时只会保留message和stack,不会包含自定义的errorType,Amplify会将这类错误标记为Lambda:Unhandled。 - 确保错误对象结构正确:必须包含
errorType和message字段,Amplify会读取这两个字段并返回给前端。 - 测试验证:在Lambda控制台测试处理器,查看返回的错误响应是否包含
errorType字段,确认格式正确后再联调前端。
内容的提问来源于stack exchange,提问作者user26954911
相关产品推荐
相关产品推荐

