Error Handling
Turn failures into predictable product states. The shared helpers report them two ways: a response envelope for messages, and a thrown Error for code that cannot continue.
Messaging responses
Every runtime message answers with the same envelope, so a caller never has to guess whether the other surface succeeded:
interface ChromeShipMessageResponse {
ok: boolean;
data?: unknown;
error?: string;
value?: string | null;
}Branch on ok instead of wrapping every call in a try/catch. A handler that returns ok: false is a normal, expected outcome — an unsupported message type, a missing element, or a rejected input.
import { sendRuntimeMessage } from "@/shared/messaging";
const response = await sendRuntimeMessage({ type: "EXTRACT_PAGE" });
if (!response.ok) {
// Show the reason next to the action that failed.
return setStatus(response.error ?? "Could not read this page.");
}
render(response.data);Errors thrown inside a handler
You do not need to catch inside a registered handler. If the handler throws, registerMessageHandler converts the failure into { ok: false, error } for the caller, using the error message when there is one and a generic message otherwise.
import { registerMessageHandler } from "@/shared/messaging";
registerMessageHandler(async (message) => {
if (message.type === "FETCH_DATA") {
const data = await fetchFromAPI(); // a throw here becomes { ok: false, error }
return { ok: true, data };
}
return { ok: false, error: "Unsupported message" };
});Thrown errors you should expect
Some helpers throw instead of returning an envelope, because the call has no meaningful partial result:
requireEnv("KEY")throws when a required public value is missing. Read it once at startup so the failure is visible during development rather than on a user action.getActiveInjectableTab()throws when the active tab is not a regularhttp(s)page and the content script cannot be reached. Treat it as a normal branch and prompt the user to open a webpage.
import { getActiveInjectableTab, sendTabMessage } from "@/shared/messaging";
try {
const tab = await getActiveInjectableTab();
await sendTabMessage(tab.id, { type: "EXTRACT_PAGE" });
} catch (error) {
setStatus(error instanceof Error ? error.message : "Open a regular webpage first.");
}Guidance
- Keep the failure message specific to the action that failed — the messaging envelope carries a string, so make it worth showing.
- Return
ok: falsefor expected outcomes and let unexpected throws surface, so a real bug is never silently reported as a user error. - Log unexpected failures to the console — ChromeShip forwards extension console output to the Studio logs.
