我正在嘗試處理 TS 中的例外。具體來說,我想用錯誤代碼 NoSuchKey 處理例外。我遇到的問題是我無法轉換錯誤或找到此屬性(沒有 NoSuchKeyError 型別)。我來自 C# 背景,所以我仍然習慣于 TS 打字。這是我所擁有的:
const client = new S3Client(...);
const command = new GetObjectCommand(...)
let response: GetObjectCommandOutput;
try {
response = await client.send(command);
}
catch (error: any) {
if (error.code === "NoSuchKey") {
console.log(error);
return;
}
}
我正在使用:@aws-sdk/client-s3 版本 3.48.0
uj5u.com熱心網友回復:
通常在 JavaScript(以及擴展的 Typescript)中,例外名稱可以通過以下方式訪問Error.name:
錯誤原型名稱
Error name.
并且根據AWS SDK 檔案,我們知道這里也是這種情況:
try {
const data = await client.send(command);
// process data.
} catch (error) {
const { requestId, cfId, extendedRequestId } = error.$metadata;
console.log({ requestId, cfId, extendedRequestId });
/**
* The keys within exceptions are also parsed.
* You can access them by specifying exception names:
* if (error.name === 'SomeServiceException') {
* const value = error.specialKeyInException;
* }
*/
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/497638.html
