Home > Blockchain >  How to handle Error Codes in AWS S3 using Typescript
How to handle Error Codes in AWS S3 using Typescript

Time:06-25

I am trying to handle an exception in TS. Specifically I want to handle exceptions with the error code NoSuchKey. The problem I am running into is that I am unable to cast the error or find this property (There is no NoSuchKeyError type). I come from a C# background so I am still getting used to TS typing. Here is what I have:

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;
  }
}

I'm using: @aws-sdk/client-s3 version 3.48.0

CodePudding user response:

Typically in JavaScript (and by extension, Typescript) exception names can be accessed via Error.name:

Error.prototype.name

 Error name.

and based on the AWS SDK documentation, we know that this is also the case here:


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;
   * }
   */
}
  • Related