Skip to content

Commit

Permalink
Add types and functions for handling HTTP errors
Browse files Browse the repository at this point in the history
  • Loading branch information
kristoferlund committed Jan 18, 2024
1 parent e02162c commit 26eca31
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {
HttpAgent,
type HttpAgentOptions,
type Identity,
type HttpDetailsResponse,
} from "@dfinity/agent";

import {
type ReactNode,
useEffect,
Expand Down Expand Up @@ -46,6 +48,39 @@ export function createActorContext<T>() {
return createContext<ActorContextType<T> | undefined>(undefined);
}

/**
* Re-export of the HttpAgentOptions type from the dfinity/agent package as it is not exported there.
*/
export class AgentHTTPResponseError extends Error {
constructor(message: string, public readonly response: HttpDetailsResponse) {
super(message);
this.name = this.constructor.name;
Object.setPrototypeOf(this, new.target.prototype);
}
}

/**
* Type guard that returns true if the error is an instance of the AgentHTTPResponseError class.
*/
export function isAgentHTTPResponseError(
error: unknown
): error is AgentHTTPResponseError {
return error instanceof Error && error.name === AgentHTTPResponseError.name;
}

/**
* Returns true if the users identity has expired. The user will need to sign in again to get a new identity.
*/
export function isIdentityExpiredError(error: unknown) {
if (!isAgentHTTPResponseError(error)) return false;
if (error.response.status === 400) {
if (error.message.includes("Specified sender delegation has expired")) {
return true;
}
}
return false;
}

/**
* Creates a React hook that can be used to access the actor from any component in the component tree. Invoke the `createUseActorHook` function with the
* React context returned by the `createActorContext` function. The function needs to be invoked with the _SERVICE type argument, where _SERVICE
Expand Down

0 comments on commit 26eca31

Please sign in to comment.