Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add from() and findDetails() to ConnectError #638

Merged
merged 11 commits into from
May 17, 2023

Conversation

timostamm
Copy link
Member

This adds two methods to ConnectError:

The static from(), which converts any error into a ConnectError, if it is not already a ConnectError:

try {
  // call an RPC
} catch (e) {
  const err: ConnectError = ConnectError.from(reason);
  console.log(err.message);
  console.log(err.code == Code.ResourceExhausted);
} 

This is a replacement for connectErrorFromReason(), which is deprecated with this PR. The static method is more discoverable, and it does not require a separate import.

And the instance method findDetails():

import {ConnectError} from "@bufbuild/connect-web";
import {LocalizedMessage} from "./error_details_pb.js";

function handle(err: ConnectError) {
  const localized = err.findDetails(LocalizedMessage)
    .find(i => i.locale === navigator.language);
  console.log(localized?.message);
}

This is a replacement for connectErrorDetails(), which is deprecated with this PR. The instance method is more discoverable, does not require a separate import, and has a more descriptive name.

The standalone function has one override accepting multiple message types that the new method does not implement. The simple workaround is to use a registry:

- connectErrorDetails(err, TypeA, TypeB);
+ import { createRegistry } from "@bufbuild/protobuf";
+ err.findDetails(createRegistry(TypeA, TypeB));

This change adds 1% to the bundle size according to our code size comparison, but the improved developer experience seems worth it.

@timostamm timostamm merged commit 4e66316 into main May 17, 2023
3 checks passed
@timostamm timostamm deleted the tstamm/add-connect-error-methods branch May 17, 2023 14:06
@timostamm timostamm mentioned this pull request May 17, 2023
@timostamm timostamm mentioned this pull request Sep 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants