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 type guard for PluginOptionError #742

Merged
merged 2 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/protoplugin/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
// limitations under the License.

export class PluginOptionError extends Error {
override name = "PluginOptionError";

constructor(option: string, reason?: unknown) {
const detail = reason !== undefined ? reasonToString(reason) : "";
super(
Expand All @@ -32,3 +34,13 @@ export function reasonToString(reason: unknown): string {
}
return String(reason);
}

export function isPluginOptionError(arg: unknown): arg is PluginOptionError {
if (!(arg instanceof Error)) {
return false;
}
if (Object.getPrototypeOf(arg) === PluginOptionError.prototype) {
return true;
}
timostamm marked this conversation as resolved.
Show resolved Hide resolved
return arg.name === "PluginOptionError";
}
9 changes: 4 additions & 5 deletions packages/protoplugin/src/run-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import type { Plugin } from "./plugin.js";
import type { ReadStream, WriteStream } from "tty";
import { CodeGeneratorRequest } from "@bufbuild/protobuf";
import { PluginOptionError, reasonToString } from "./error.js";
import { isPluginOptionError, reasonToString } from "./error.js";

/**
* Run a plugin with Node.js.
Expand Down Expand Up @@ -49,10 +49,9 @@ export function runNodeJs(plugin: Plugin): void {
})
.then(() => process.exit(0))
.catch((reason) => {
const message =
reason instanceof PluginOptionError
? reason.message
: reasonToString(reason);
const message = isPluginOptionError(reason)
? reason.message
: reasonToString(reason);
process.stderr.write(`${plugin.name}: ${message}\n`);
process.exit(1);
return;
Expand Down
Loading