This repository has been archived by the owner on Dec 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(backend): cleanly handle errors in cli (#365)
- Loading branch information
1 parent
f1c34be
commit 3a895e8
Showing
1 changed file
with
31 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,39 @@ | ||
import { parseArgs } from "@std/cli/parse-args"; | ||
import { executeCommand } from "./execute.ts"; | ||
import { commandSchema } from "./execute.ts"; | ||
import { runShutdown } from "../toolchain/utils/shutdown_handler.ts"; | ||
import { printError, UserError } from "../toolchain/error/mod.ts"; | ||
|
||
const args = parseArgs(Deno.args); | ||
const commandJson = args["command"]; | ||
let exitCode = 0; | ||
try { | ||
// Parse flags | ||
const args = parseArgs(Deno.args); | ||
const commandJson = args["command"]; | ||
if (!commandJson) { | ||
throw new UserError("Missing --command argument"); | ||
} | ||
|
||
if (!commandJson) { | ||
console.error("Missing --command argument"); | ||
Deno.exit(1); | ||
} | ||
// Parse coman | ||
let command; | ||
try { | ||
command = JSON.parse(commandJson); | ||
} catch (cause) { | ||
throw new UserError("Invalid command JSON", { cause }); | ||
} | ||
|
||
try { | ||
const command = JSON.parse(commandJson); | ||
const validatedCommand = commandSchema.parse(command); | ||
await executeCommand(validatedCommand); | ||
} catch (error) { | ||
if (error instanceof SyntaxError) { | ||
console.error("Invalid JSON in --command argument"); | ||
} else { | ||
console.error("Invalid command:", error); | ||
// Validate command | ||
let validatedCommand = commandSchema.safeParse(command); | ||
if (!validatedCommand.success) { | ||
throw new UserError("Command violates schema", { details: JSON.stringify(validatedCommand.error, null, 2) }); | ||
} | ||
Deno.exit(1); | ||
|
||
// Execute command | ||
await executeCommand(validatedCommand.data); | ||
} catch (err) { | ||
printError(err); | ||
exitCode = 1; | ||
} finally { | ||
runShutdown(); | ||
} | ||
|
||
Deno.exit(exitCode); |