AWS JavaScript SDK v3 with TypeScript 4.4.2 and @types/node 16.7.10 thrown error type

Viewed 1643

I updated today (after a couple of months) my package.json file with the latest package versions, I think the ones impacting this error are the ones in the subject of the question.

Some error handling blocks as the following one

try {
  // ...
} catch(err) {
  console.log(err.message);
}

stopped working due to TypeScript error 2571: Object is of type 'unknown'.

Nice! I just had to apply following simple change:

try {
  // ...
} catch(err) {
  console.log(err instanceof Error ? err.message : JSON.stringify(err));
}

not only my code started to work once again, but I feel my code is more resilient as well.

The problem comes when I try to handle an error thrown from the AWS SDK v3.

import { CloudWatchLogs, ResourceNotFoundException } from "@aws-sdk/client-cloudwatch-logs";

const cwl = new CloudWatchLogs({ region: "us-east-2" });

try {
  const logGroupName = "...";
  const logStreamName = "...";
  const { events } = await cwl.getLogEvents({ logGroupName, logStreamName });

  // ...
} catch(err) {
  if(! (err instanceof ResourceNotFoundException)) console.log(err);
}

In the simplified (I'm not handling pagination) above code sample I simply want to ignore the ResourceNotFoundException, but the err instanceof ResourceNotFoundException check doesn't compile since ResourceNotFoundException is an interface rather than a class.

I found this answer which seems could help me.

The question is: should I write an instanceOf\w+Exception function (sorry for the regexp) for each AWS exception I need to handle, or is there a common and reusable way provided by AWS?

The main reason why I'm seeking for this is not that I'm lazy (and I am), but if I write my own instanceOf\w+Exception functions inspecting the AWS SDK source code, my functions may stop working if Amazon will change something in the SDK.

2 Answers

I found this issue: I strongly suspect, at the moment, the answer is simply: no, there isn't.

Edit: the same issue was solved and now we can use the instanceof operator (I have not yet tested it).

Update 2022

AWS SDK v3 is now using instanceof and deprecating the typescript sdkerror

https://aws.amazon.com/blogs/developer/service-error-handling-modular-aws-sdk-js

import {
  InvalidSignatureException,
  ResourceNotFoundException,
  FooServiceException,
} from "@aws-sdk/client-foo";

Obviously replace foo by the client you are using

try {
  await client.send(someCommand);
} catch (e) {
  if (e instanceof InvalidSignatureException) {
    // Handle InvalidSignatureException
  } else if (e instanceof ResourceNotFoundException) {
    // Handle ResourceNotFoundException
  } else if (e instanceof FooServiceException) {
    // Handle all other server-side exceptions from Foo service
  } else {
    // Other errors
  }
}
Related