Skip to content

Commit

Permalink
Format provider errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jribbink committed Feb 5, 2025
1 parent 31df38b commit c2932bb
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
10 changes: 9 additions & 1 deletion packages/fcl-ethereum-provider/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from "./types/provider"
import {RpcProcessor} from "./rpc/rpc-processor"
import {EventDispatcher} from "./events/event-dispatcher"
import {RpcError, RpcErrorCode} from "./util/errors"

export class FclEthereumProvider implements Eip1193Provider {
constructor(
Expand All @@ -26,7 +27,14 @@ export class FclEthereumProvider implements Eip1193Provider {
const result = await this.rpcProcessor.handleRequest({method, params})
return result
} catch (error) {
throw new Error(`Request failed: ${(error as Error).message}`)
if (error instanceof RpcError) {
throw error
} else {
throw new RpcError({
code: RpcErrorCode.InternalError,
cause: error,
})
}
}
}

Expand Down
69 changes: 69 additions & 0 deletions packages/fcl-ethereum-provider/src/util/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// EIP-1474 error codes
export enum RpcErrorCode {
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603,
}

// EIP-1193 error codes
export enum ProviderErrorCode {
UserRejectedRequest = 4001,
Unauthorized = 4100,
UnsupportedMethod = 4200,
Disconnected = 4900,
}

// EI-1474 error messages used as default
export const RpcErrorMessage: Record<RpcErrorCode, string> = {
[-32700]: "Parse error",
[-32600]: "Invalid request",
[-32601]: "Method not found",
[-32602]: "Invalid params",
[-32603]: "Internal error",
}

// EIP-1193 error messages used as default
export const ProviderErrorMessage: Record<ProviderErrorCode, string> = {
[4001]: "User rejected request",
[4100]: "Unauthorized",
[4200]: "Unsupported method",
[4900]: "Disconnected",
}

export class RpcError extends Error {
public code: RpcErrorCode
public data?: unknown

constructor({
code,
message,
data,
cause,
}: {
code: RpcErrorCode
message?: string
data?: unknown
cause?: any
}) {
if (!RpcErrorMessage[code]) {
throw new Error(`Invalid RPC error code: ${code}`)
}
super(message || RpcErrorMessage[code])
this.code = code
this.data = data
if (cause) {
this.stack = `${this.stack}\nCaused by: ${cause.stack}`
}
}
}

export class ProviderError extends Error {
public code: ProviderErrorCode

constructor(code: ProviderErrorCode, message?: string) {
super(message || ProviderErrorMessage[code])
this.code = code
}
}

0 comments on commit c2932bb

Please sign in to comment.