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

V2: Throw errors in ReflectMessage instead of returning them #882

Merged
merged 1 commit into from
Jun 6, 2024

Conversation

timostamm
Copy link
Member

@timostamm timostamm commented Jun 6, 2024

The reflection API provided by ReflectMessage, ReflectList, and ReflectMap validates a value before setting it. The methods return an error for an invalid value. For example:

import { UserDesc } from "./gen/ts/extra/example_pb.js";
import { create } from "@bufbuild/protobuf";
import { reflect } from "@bufbuild/protobuf/reflect";

const user = create(UserDesc);
const msg = reflect(UserDesc, user);

const err = msg.set(UserDesc.field.firstName, 123);
console.log(err.message); // expected string, got 123

The firstName field is a string, and calling msg.set returns an error.

While this pattern works well, returning errors is very uncommon. This PR changes the behavior to throw errors instead. To handle the error, the example above changes to:

const user = create(UserDesc);
const msg = reflect(UserDesc, user);

try {
  msg.set(UserDesc.field.firstName, 123);
} catch (e) {
  if (isFieldError(e)) {
    console.log(e.message); // expected string, got 123
  }
}

assertOwn(this.message, field);
if (this.check) {
const err = checkField(field, value);
if (err) {
return err;
throw err;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could throw in checkField, but the function is internal, so we can punt on it until there is a really good reason do change the function.

@timostamm timostamm merged commit 4d90100 into v2 Jun 6, 2024
7 checks passed
@timostamm timostamm deleted the tstamm/reflect-throw branch June 6, 2024 14:35
@timostamm timostamm mentioned this pull request Jun 24, 2024
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.

2 participants