Package detail

@metamask/rpc-errors

MetaMask1.4mMIT7.0.2

Ethereum RPC and Provider errors

rpc, ethereum, errors, utility

readme

@metamask/rpc-errors

JSON-RPC errors, including for Ethereum JSON RPC and Ethereum Provider, and making unknown errors compliant with either spec.

Installation

yarn add @metamask/rpc-errors

or

npm install @metamask/rpc-errors

Usage

import { rpcErrors, providerErrors } from '@metamask/rpc-errors';

throw rpcErrors.invalidRequest();
// or
throw providerErrors.unauthorized('my custom message');

Supported Errors

API

import { rpcErrors, providerErrors } from '@metamask/rpc-errors';

// JSON-RPC errors and Ethereum EIP-1474 errors are namespaced under "rpcErrors"
response.error = rpcErrors.methodNotFound({
  message: optionalCustomMessage,
  data: optionalData,
});

// Ethereum EIP-1193 Provider errors namespaced under "providerErrors"
response.error = providerErrors.unauthorized({
  message: optionalCustomMessage,
  data: optionalData,
});

// each error getter takes a single "opts" argument
// for most errors, this can be replaced with a single string, which becomes
// the error message
response.error = providerErrors.unauthorized(customMessage);

// if an error getter accepts a single string, all arguments can be omitted
response.error = providerErrors.unauthorized();
response.error = providerErrors.unauthorized({});

// omitting the message will produce an error with a default message per
// the relevant spec

// omitting the data argument will produce an error without a
// "data" property

// the JSON RPC 2.0 server error requires a valid code
response.error = rpcErrors.server({
  code: -32031,
});

// custom Ethereum Provider errors require a valid code and message
// valid codes are integers i such that: 1000 <= i <= 4999
response.error = providerErrors.custom({
  code: 1001,
  message: 'foo',
});

Parsing Unknown Errors

// this is useful for ensuring your errors are standardized
import { serializeError } from '@metamask/rpc-errors'

// if the argument is not a valid error per any supported spec,
// it will be added as error.data.originalError
response.error = serializeError(maybeAnError)

// you can add a custom fallback error code and message if desired
const fallbackError = { code: 4999, message: 'My custom error.' }
response.error = serializeError(maybeAnError, fallbackError)

// Note: if the original error has a "message" property, it will take
// precedence over the fallback error's message

// the default fallback is:
{
  code: -32603,
  message: 'Internal JSON-RPC error.'
}

Other Exports

/**
 * Classes
 */
import { JsonRpcError, EthereumProviderError } from '@metamask/rpc-errors';

/**
 * getMessageFromCode and errorCodes
 */
import { getMessageFromCode, errorCodes } from '@metamask/rpc-errors';

// get the default message string for the given code, or a fallback message if
// no message exists for the given code
const message1 = getMessageFromCode(someCode);

// you can specify your own fallback message
const message2 = getMessageFromCode(someCode, myFallback);
// it can be anything, use at your own peril
const message3 = getMessageFromCode(someCode, null);

// {
//   rpcErrors: { [errorName]: code, ... },
//   providerErrors: { [errorName]: code, ... },
// }
const code1 = rpcErrors.parse;
const code2 = providerErrors.userRejectedRequest;

// all codes in errorCodes have default messages
const message4 = getMessageFromCode(code1);
const message5 = getMessageFromCode(code2);

Contributing

Setup

  • Install Node.js version 18
    • If you are using nvm (recommended) running nvm use will automatically choose the right node version for you.
  • Install Yarn v3
  • Run yarn install to install dependencies and run any required post-install scripts

Testing and Linting

Run yarn test to run the tests once. To run tests on file changes, run yarn test:watch.

Run yarn lint to run the linter, or run yarn lint:fix to run the linter and fix any automatically fixable issues.

Release & Publishing

The project follows the same release process as the other libraries in the MetaMask organization. The GitHub Actions action-create-release-pr and action-publish-release are used to automate the release process; see those repositories for more information about how they work.

  1. Choose a release version.

  2. The release version should be chosen according to SemVer. Analyze the changes to see whether they include any breaking changes, new features, or deprecations, then choose the appropriate SemVer version. See the SemVer specification for more information.

  3. If this release is backporting changes onto a previous release, then ensure there is a major version branch for that version (e.g. 1.x for a v1 backport release).

  4. The major version branch should be set to the most recent release with that major version. For example, when backporting a v1.0.2 release, you'd want to ensure there was a 1.x branch that was set to the v1.0.1 tag.

  5. Trigger the workflow_dispatch event manually for the Create Release Pull Request action to create the release PR.

  6. For a backport release, the base branch should be the major version branch that you ensured existed in step 2. For a normal release, the base branch should be the main branch for that repository (which should be the default value).

  7. This should trigger the action-create-release-pr workflow to create the release PR.

  8. Update the changelog to move each change entry into the appropriate change category (See here for the full list of change categories, and the correct ordering), and edit them to be more easily understood by users of the package.

  9. Generally any changes that don't affect consumers of the package (e.g. lockfile changes or development environment changes) are omitted. Exceptions may be made for changes that might be of interest despite not having an effect upon the published package (e.g. major test improvements, security improvements, improved documentation, etc.).

  10. Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
  11. Consolidate related changes into one change entry if it makes it easier to explain.
  12. Run yarn auto-changelog validate --rc to check that the changelog is correctly formatted.

  13. Review and QA the release.

  14. If changes are made to the base branch, the release branch will need to be updated with these changes and review/QA will need to restart again. As such, it's probably best to avoid merging other PRs into the base branch while review is underway.

  15. Squash & Merge the release.

  16. This should trigger the action-publish-release workflow to tag the final release commit and publish the release on GitHub.

  17. Publish the release on npm.

  18. Wait for the publish-release GitHub Action workflow to finish. This should trigger a second job (publish-npm), which will wait for a run approval by the npm publishers team.

  19. Approve the publish-npm job (or ask somebody on the npm publishers team to approve it for you).
  20. Once the publish-npm job has finished, check npm to verify that it has been published.

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

Unreleased

7.0.2

Changed

  • Bump @metamask/utils from ^10.0.0 to ^11.0.1 (#166)

7.0.1

Changed

  • Bump @metamask/utils from ^9.0.0 to ^10.0.0 (#161)

7.0.0

Changed

  • BREAKING: Preserve original messages during error serialization by default (#158)
    • The behavior introduced in 5.0.0 of overwriting the original message is available by passing shouldPreserveMessage: false to serializeError().
  • BREAKING: Bump minimum Node.js version from 16 to 18 (#154)

6.4.0

Changed

  • Migrate to ts-bridge (#152)
    • Migrates to ts-bridge from tsup, which may resolve issues when importing this package in CommonJS or ESM.

6.3.1

Changed

  • Bump @metamask/utils from ^8.3.0 to ^9.0.0 (#147)

6.3.0

Added

  • Expose error causes as cause property (#140)
    • JsonRpcError objects already had a .data.cause property. It is now exposed as .cause in order to to be recognized as ES Causes.

6.2.1

Fixed

  • Export OptionalDataWithOptionalCause type (#135)

6.2.0

Added

  • Add ESM build (#133)

Changed

  • Update @metamask/utils from ^8.1.0 to ^8.3.0 (#133)

6.1.0

Changed

  • Update dependency @metamask/utils from ^8.0.0 to ^8.1.0 (#108)

Fixed

  • Exclude dist/__fixtures__ files from published package (#114)

6.0.0

Changed

  • Make Data type-parameter optional in JsonRpcError (#102)

Fixed

  • BREAKING: undefined is now not recognized as valid JSON value
    • Update dependency @metamask/utils from ^5.0.0 to ^8.0.0 (#101)

5.1.1

Fixed

  • Allow passing unknown values as cause (#91)
    • Prevously, only Error instances were allowed, but any value can be thrown as error

5.1.0

Added

  • Allow passing a cause to predefined error functions (#83)
    • This allows passing an Error instance as cause, by using { data: { cause: /* some error */ } }
    • The error will be properly serialised when calling serialize

5.0.0

Changed

  • BREAKING: Bump minimum version to Node 16 (#68)
  • BREAKING: Rewrite error serialization (#61)
    • Allows errors that conform to the JsonRpcError type
    • If errors don't conform to the type, the error will be wrapped in an internal error and the original error will be available as data.cause
  • BREAKING: Rename exports to be more generic (#75)
    • JSON-RPC errors and Ethereum EIP-1474 errors are namespaced under "rpcErrors"
    • Ethereum EIP-1193 Provider errors are namespaced under "providerErrors"
  • BREAKING: Target ES2020 (#77)
  • Rename package to @metamask/rpc-errors (#67)

4.0.3 - 2021-03-10

Fixed

  • Correctly type ethErrors getter function argument objects as optional (#36)

4.0.2 - 2020-11-17

Changed

  • Mark the data property of EthereumRpcError and EthereumProviderError as optional rather than T | undefined (#34)

Fixed

  • Correctly type SerializedEthereumRpcError.stack as string, if present (#34)

4.0.1 - 2020-11-03

Changed

  • Updated README.md (#30)

4.0.0 - 2020-11-02

Changed

  • BREAKING: ERROR_CODES export renamed to errorCodes (#28)
  • BREAKING: ethErrors getters will now throw an error if passed a truthy, non-string message (#28)
  • Updated TypeScript types for all exports (#28)

3.0.0 - 2020-07-29

Changed

  • BREAKING: Second argument of serializeError is now an options object (#22)
  • Error stacks are no longer serialized by default by serializeError (#22)

2.1.1 - 2020-05-12

Changed

  • Prevent unnecessary files from being published (#17)

2.1.0 - 2020-05-11

Added

  • New/missing errors:
    • ethErrors.provider (EIP-1193)
      • .disconnected, 4900
      • .chainDisconnected, 4901
    • ethErrors.rpc (EIP-1474)
      • .limitExceeded, -32005

Changed

  • Rename package to eth-rpc-errors

2.0.2 - 2020-02-12

Changed

  • Fix faulty null checks throughout codebase (764832d)

2.0.1 - 2020-01-31

Added

  • Error codes in docstrings (5452001)

2.0.0 - 2019-09-26

Changed

  • Exports
    • errors renamed ethErrors
    • JsonRpcError renamed EthereumRpcError
    • EthJsonRpcError renamed EthereumProviderError
      • It is still a subclass of EthereumRpcError
    • TypeScript
      • Renamed affected interfaces
  • ethErrors
    • Added missing EIP-1474 errors
      • Added corresponding codes and messages
    • Namespacing
      • EIP-1474 (which includes JSON RPC 2.0) errors now namespaced under ethErrors.rpc
        • JSON RPC 2.0 errors were formerly under errors.jsonRpc
      • EIP-1193 errors now namespaced under ethErrors.provider
        • Formerly under errors.eth
    • Most error getters now take a single, optional opts argument, which is either a string or an object
      • If a string, it becomes the error message
      • If an object, it should have the form: { message?: string, data?: any }
      • Special Cases
        • ethErrors.rpc.server must receive a single object of the form:
          • `{ code: number, message?: string, data?: any }
        • ethErrors.provider.custom must receive a single of the form:
          • `{ code: number, message: string, data?: any }
  • TypeScript
    • Updated affected interfaces

1.1.0 - 2019-09-16

Changed

  • serializeError
    • If the object passed to the function has a .message property, it will preferred over the .message property of the fallback error when creating the returned serialized error object