Skip to content

Commit

Permalink
Add type guard for PluginOptionError (#742)
Browse files Browse the repository at this point in the history
This adds a type guard function for `PluginOptionError` so that
`instanceof` is no longer used. For additional details, see #713
  • Loading branch information
smaye81 authored Mar 11, 2024
1 parent 7957a10 commit 00c7213
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
9 changes: 9 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,10 @@ export function reasonToString(reason: unknown): string {
}
return String(reason);
}

export function isPluginOptionError(arg: unknown): arg is PluginOptionError {
if (!(arg instanceof Error)) {
return false;
}
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

0 comments on commit 00c7213

Please sign in to comment.