Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/warm-pans-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@smithy/smithy-client": minor
---

feat: type check helper method to to know if something is an instance of the ServiceException class
33 changes: 33 additions & 0 deletions packages/smithy-client/src/exceptions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,39 @@ it("ExceptionOptionType allows specifying message", () => {
expect(exception.code).toBe("code");
});

describe("ServiceException.isInstance", () => {
it("should return true for valid ServiceException instances", () => {
const error = new ServiceException({
name: "Error",
$fault: "client",
$metadata: {},
});
expect(ServiceException.isInstance(error)).toBe(true);
});

it("should return true for valid duck-typed objects", () => {
const duckTyped = {
$fault: "server",
$metadata: {},
};
expect(ServiceException.isInstance(duckTyped)).toBe(true);
});

it("should return false for null or undefined", () => {
expect(ServiceException.isInstance(null)).toBe(false);
expect(ServiceException.isInstance(undefined)).toBe(false);
});

it("should return false for invalid $fault values", () => {
expect(ServiceException.isInstance({ $fault: "invalid", $metadata: {} })).toBe(false);
});

it("should return false for missing properties", () => {
expect(ServiceException.isInstance({ $fault: "client" })).toBe(false);
expect(ServiceException.isInstance({ $metadata: {} })).toBe(false);
});
});

describe("decorateServiceException", () => {
const exception = new ServiceException({
name: "Error",
Expand Down
13 changes: 13 additions & 0 deletions packages/smithy-client/src/exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ export class ServiceException extends Error implements SmithyException, Metadata
this.$fault = options.$fault;
this.$metadata = options.$metadata;
}

/**
* Checks if a value is an instance of ServiceException (duck typed)
*/
public static isInstance(value: unknown): value is ServiceException {
if (!value) return false;
const candidate = value as ServiceException;
return (
Boolean(candidate.$fault) &&
Boolean(candidate.$metadata) &&
(candidate.$fault === "client" || candidate.$fault === "server")
);
}
}

/**
Expand Down
Loading