fix(cli): end every error message with what to do next (#58)

* fix(cli): end every error message with what to do next

Docker, snapshot, update and config profile errors now say how to recover (check Docker, run doctor or status, fix or delete the profile file, pass the missing profile name) instead of stopping at the failure. A test keeps new error messages to the convention.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(cli): keep the next step after docker's own output and name the instance in snapshot hints

Docker's error output ends in a newline and can span lines, which read as 'already has a next step' and hid the hint. The exception now knows whether its text is docker's output or the CLI's own advice. Snapshot hints select the same instance again.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 23:02:30 -05:00
1 parent 6a74d7d2d5
commit bd4fa0f134
18 files changed
+252 -31

No files matched your search

@@ -54,7 +54,7 @@ public class LogsCommand implements Callable<Integer> {
return 1; return 1;
} }
} catch (DockerException e) { } catch (DockerException e) {
printer.error("Failed to inspect container: " + e.getMessage()); printer.error("Failed to inspect container: " + e.withNextStep(DockerClient.CHECK_DOCKER));
return 1; return 1;
} }
@@ -66,7 +66,7 @@ public class LogsCommand implements Callable<Integer> {
docker.streamLogs(global.container, follow, tail, since); docker.streamLogs(global.container, follow, tail, since);
return 0; return 0;
} catch (DockerException e) { } catch (DockerException e) {
printer.error("Failed to fetch logs: " + e.getMessage()); printer.error("Failed to fetch logs: " + e.withNextStep(DockerClient.CHECK_DOCKER));
return 1; return 1;
} }
} }
@@ -152,10 +152,9 @@ public class ResetCommand implements Callable<Integer> {
printer.error("Resetting state is not available on this " + profile.displayName() + " server version.\n" printer.error("Resetting state is not available on this " + profile.displayName() + " server version.\n"
+ "Restart it without --persist for a clean state, or track progress: " + profile.serverRepo() + "/issues"); + "Restart it without --persist for a clean state, or track progress: " + profile.serverRepo() + "/issues");
} else { } else {
String message = "Failed to reset " + profile.displayName() + ": " + e.getMessage();
// Connection errors already say what to do; others get the status hint. // Connection errors already say what to do; others get the status hint.
printer.error(message.contains("\n") ? message printer.error("Failed to reset " + profile.displayName() + ": " + e.getMessage(),
: message + "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator."); "Run '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator.");
} }
return 1; return 1;
} }
@@ -331,7 +331,11 @@ public class StartCommand implements Callable<Integer> {
printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/"); printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/");
return 1; return 1;
} }
printer.error("Failed to inspect container: " + e.getMessage() + socketGuidance(daemon)); // The socket guidance, when there is any, is the next step; otherwise the general one.
String guidance = socketGuidance(daemon);
printer.error("Failed to inspect container: " + (guidance.isEmpty()
? e.withNextStep(DockerClient.CHECK_DOCKER)
: e.getMessage().strip() + guidance));
return 1; return 1;
} }
@@ -360,7 +364,8 @@ public class StartCommand implements Callable<Integer> {
String id = docker.startContainer(args); String id = docker.startContainer(args);
printer.println(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); printer.println(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")");
} catch (DockerException e) { } catch (DockerException e) {
printer.error("Failed to start container: " + e.getMessage()); printer.error("Failed to start container: " + e.getMessage(),
"Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port.");
return 1; return 1;
} }
@@ -57,7 +57,7 @@ public class StopCommand implements Callable<Integer> {
return 0; return 0;
} }
} catch (DockerException e) { } catch (DockerException e) {
printer.error("Failed to inspect container: " + e.getMessage()); printer.error("Failed to inspect container: " + e.withNextStep(DockerClient.CHECK_DOCKER));
return 1; return 1;
} }
@@ -66,7 +66,7 @@ public class StopCommand implements Callable<Integer> {
docker.stopContainer(global.container, timeout); docker.stopContainer(global.container, timeout);
printer.println(Ansi.green("Stopped.")); printer.println(Ansi.green("Stopped."));
} catch (DockerException e) { } catch (DockerException e) {
printer.error("Failed to stop container: " + e.getMessage()); printer.error("Failed to stop container: " + e.withNextStep(DockerClient.CHECK_DOCKER));
return 1; return 1;
} }
@@ -75,7 +75,7 @@ public class StopCommand implements Callable<Integer> {
docker.removeContainer(global.container); docker.removeContainer(global.container);
printer.println("Container removed."); printer.println("Container removed.");
} catch (DockerException e) { } catch (DockerException e) {
printer.error("Failed to remove container: " + e.getMessage()); printer.error("Failed to remove container: " + e.withNextStep(DockerClient.CHECK_DOCKER));
return 1; return 1;
} }
} }
@@ -142,10 +142,10 @@ public class UpdateCommand implements Callable<Integer> {
+ Ansi.gray(" (" + binary + ")")); + Ansi.gray(" (" + binary + ")"));
return 0; return 0;
} catch (UpdateException e) { } catch (UpdateException e) {
printer.error(e.getMessage()); printer.error(e.getMessage(), "To reinstall instead, see https://floci.io.");
return check ? 2 : 1; // --check keeps 1 for "update available" return check ? 2 : 1; // --check keeps 1 for "update available"
} catch (Exception e) { } catch (Exception e) {
printer.error("update failed: " + e.getMessage() + "\nCheck your network connection and re-run 'floci update'."); printer.error("update failed: " + e.getMessage(), "Check your network connection and re-run 'floci update'.");
return check ? 2 : 1; return check ? 2 : 1;
} }
} }
@@ -26,7 +26,7 @@ public class ConfigDefaultProductCommand implements Callable<Integer> {
public Integer call() { public Integer call() {
Printer printer = global.printer(); Printer printer = global.printer();
if (!"aws".equals(product) && !"az".equals(product) && !"gcp".equals(product) && !"oci".equals(product)) { if (!"aws".equals(product) && !"az".equals(product) && !"gcp".equals(product) && !"oci".equals(product)) {
printer.error("Unknown product '" + product + "'. Use: aws, az, gcp, oci"); printer.error("Unknown product '" + product + "'.\nUse one of: aws, az, gcp, oci.");
return 1; return 1;
} }
GlobalConfigStore store = new GlobalConfigStore(); GlobalConfigStore store = new GlobalConfigStore();
@@ -37,7 +37,8 @@ public class ConfigDefaultProductCommand implements Callable<Integer> {
printer.println(Ansi.gray("Config saved to: " + store.configFilePath())); printer.println(Ansi.gray("Config saved to: " + store.configFilePath()));
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not save config: " + e.getMessage()); printer.error("Could not save config: " + e.getMessage(),
"Check that " + store.configFilePath().getParent() + " is writable and re-run the command.");
return 1; return 1;
} }
} }
@@ -87,7 +87,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
case "create" -> createProfile(printer, store); case "create" -> createProfile(printer, store);
case "delete" -> deleteProfile(printer, store); case "delete" -> deleteProfile(printer, store);
default -> { default -> {
printer.error("Unknown action '" + action + "'. Use: list, show, create, delete"); printer.error("Unknown action '" + action + "'.\nUse one of: list, show, create, delete.");
yield 1; yield 1;
} }
}; };
@@ -138,16 +138,20 @@ public class ConfigProfileCommand implements Callable<Integer> {
} }
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not list profiles: " + e.getMessage()); printer.error("Could not list profiles: " + e.getMessage(),
"Check the files under ~/.floci/profiles and re-run the command.");
return 1; return 1;
} }
} }
private int showProfile(Printer printer, ProfileStore store) { private int showProfile(Printer printer, ProfileStore store) {
if (name == null) { printer.error("Profile name required."); return 1; } if (name == null) { printer.error(nameRequired()); return 1; }
try { try {
var profile = store.get(name); var profile = store.get(name);
if (profile.isEmpty()) { printer.error("Profile '" + name + "' not found."); return 1; } if (profile.isEmpty()) {
printer.error("Profile '" + name + "' not found.\nRun '" + this.profile.commandPrefix() + " config profile list' to see available profiles.");
return 1;
}
Profile p = profile.get(); Profile p = profile.get();
ProfileDefaultValueProvider.warnAboutUnknownKeys(store, name, p); ProfileDefaultValueProvider.warnAboutUnknownKeys(store, name, p);
printer.println(Ansi.bold("Profile: ") + p.name); printer.println(Ansi.bold("Profile: ") + p.name);
@@ -160,16 +164,16 @@ public class ConfigProfileCommand implements Callable<Integer> {
if (p.namespace != null) printer.println(" namespace: " + p.namespace); if (p.namespace != null) printer.println(" namespace: " + p.namespace);
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not read profile: " + e.getMessage()); printer.error("Could not read profile: " + e.getMessage(), "Fix or delete the profile file, then re-run the command.");
return 1; return 1;
} }
} }
private int createProfile(Printer printer, ProfileStore store) { private int createProfile(Printer printer, ProfileStore store) {
if (name == null) { printer.error("Profile name required."); return 1; } if (name == null) { printer.error(nameRequired()); return 1; }
try { try {
if (store.get(name).isPresent()) { if (store.get(name).isPresent()) {
printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.existingFile(name)); printer.error("Profile '" + name + "' already exists.\nDelete it first, or edit " + store.existingFile(name) + ".");
return 1; return 1;
} }
if (port != null && (port < 1 || port > 65535)) { if (port != null && (port < 1 || port > 65535)) {
@@ -196,7 +200,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
printer.println(Ansi.gray("Start it with: " + profile.commandPrefix() + " start --profile " + name)); printer.println(Ansi.gray("Start it with: " + profile.commandPrefix() + " start --profile " + name));
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not create profile: " + e.getMessage()); printer.error("Could not create profile: " + e.getMessage(), "Check that ~/.floci/profiles is writable and re-run the command.");
return 1; return 1;
} }
} }
@@ -255,7 +259,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
} }
private int deleteProfile(Printer printer, ProfileStore store) { private int deleteProfile(Printer printer, ProfileStore store) {
if (name == null) { printer.error("Profile name required."); return 1; } if (name == null) { printer.error(nameRequired()); return 1; }
try { try {
List<Path> removed = store.delete(name); List<Path> removed = store.delete(name);
if (removed.isEmpty()) { if (removed.isEmpty()) {
@@ -268,8 +272,12 @@ public class ConfigProfileCommand implements Callable<Integer> {
printer.println(Ansi.green("Deleted") + " profile '" + name + "'" + files); printer.println(Ansi.green("Deleted") + " profile '" + name + "'" + files);
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not delete profile: " + e.getMessage()); printer.error("Could not delete profile: " + e.getMessage(), "Check that ~/.floci/profiles is writable and re-run the command.");
return 1; return 1;
} }
} }
private String nameRequired() {
return "Profile name required.\nPass it after the action, for example '" + profile.commandPrefix() + " config profile " + action + " dev'.";
}
} }
@@ -48,7 +48,7 @@ public class ConfigValidateCommand implements Callable<Integer> {
Path composeFile = resolveComposeFile(); Path composeFile = resolveComposeFile();
if (composeFile == null) { if (composeFile == null) {
printer.error("No docker-compose file found. Pass --file <path> or run in a directory with docker-compose.yml."); printer.error("No docker-compose file found.\nPass --file <path>, or run in a directory with docker-compose.yml.");
return 1; return 1;
} }
@@ -56,7 +56,8 @@ public class ConfigValidateCommand implements Callable<Integer> {
try { try {
content = Files.readString(composeFile); content = Files.readString(composeFile);
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not read " + composeFile + ": " + e.getMessage()); printer.error("Could not read " + composeFile + ": " + e.getMessage(),
"Check the file's permissions, or pass another with --file.");
return 1; return 1;
} }
@@ -51,7 +51,8 @@ public class SnapshotDeleteCommand implements Callable<Integer> {
printer.error("Snapshot API not available on this server version.\n" + printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues"); "Track progress: " + profile.serverRepo() + "/issues");
} else { } else {
printer.error("Failed to delete snapshot: " + e.getMessage()); printer.error("Failed to delete snapshot: " + e.getMessage(),
"Run '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator.");
} }
return 1; return 1;
} }
@@ -58,7 +58,8 @@ public class SnapshotListCommand implements Callable<Integer> {
printer.error("Snapshot API not available on this server version.\n" + printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues"); "Track progress: " + profile.serverRepo() + "/issues");
} else { } else {
printer.error("Failed to list snapshots: " + e.getMessage()); printer.error("Failed to list snapshots: " + e.getMessage(),
"Run '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator.");
} }
return 1; return 1;
} }
@@ -51,7 +51,8 @@ public class SnapshotLoadCommand implements Callable<Integer> {
printer.error("Snapshot API not available on this server version.\n" + printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues"); "Track progress: " + profile.serverRepo() + "/issues");
} else { } else {
printer.error("Failed to load snapshot: " + e.getMessage()); printer.error("Failed to load snapshot: " + e.getMessage(),
"Run '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator.");
} }
return 1; return 1;
} }
@@ -58,7 +58,8 @@ public class SnapshotSaveCommand implements Callable<Integer> {
printer.error("Snapshot API not available on this server version.\n" + printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues"); "Track progress: " + profile.serverRepo() + "/issues");
} else { } else {
printer.error("Failed to save snapshot: " + e.getMessage()); printer.error("Failed to save snapshot: " + e.getMessage(),
"Run '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator.");
} }
return 1; return 1;
} }
@@ -27,6 +27,9 @@ public class DockerClient {
/** How long a non-streaming docker call may take before it is killed. */ /** How long a non-streaming docker call may take before it is killed. */
public static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(30); public static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(30);
/** The next step for a failed docker call. */
public static final String CHECK_DOCKER = "Check that Docker is running ('docker info') and re-run the command.";
private final String binary; private final String binary;
private final Duration timeout; private final Duration timeout;
@@ -252,7 +255,7 @@ public class DockerClient {
String out = stdout.join(); String out = stdout.join();
String err = stderr.join(); String err = stderr.join();
if (proc.exitValue() != 0) { if (proc.exitValue() != 0) {
throw new DockerException(err.isBlank() ? out : err); throw DockerException.ofOutput(err.isBlank() ? out : err);
} }
return out; return out;
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -1,7 +1,30 @@
package io.floci.cli.docker; package io.floci.cli.docker;
public class DockerException extends Exception { public class DockerException extends Exception {
private final boolean advised;
/** An error in this CLI's own words; a second line in it is its next step. */
public DockerException(String message) { public DockerException(String message) {
this(message, message != null && message.strip().contains("\n"));
}
private DockerException(String message, boolean advised) {
super(message); super(message);
this.advised = advised;
}
/**
* An error that is docker's own output. However many lines it has, none of them is advice
* from this CLI, so it never counts as already saying what to do next.
*/
public static DockerException ofOutput(String output) {
return new DockerException(output == null ? "" : output.strip(), false);
}
/** The message followed by {@code nextStep}, unless the message already ends with its own. */
public String withNextStep(String nextStep) {
String message = getMessage() == null ? "" : getMessage().strip();
return advised ? message : message + "\n" + nextStep;
} }
} }
@@ -41,6 +41,16 @@ public final class Printer {
err.println(Ansi.red("Error: ") + message); err.println(Ansi.red("Error: ") + message);
} }
/**
* Reports {@code message} followed by {@code nextStep}, unless the message already carries its
* own (a second line), as messages from DockerException or FlociException often do.
*/
public void error(String message, String nextStep) {
// A trailing newline is not a second line: forwarded output often ends with one.
String text = message.stripTrailing();
error(text.contains("\n") ? text : text + "\n" + nextStep);
}
public void warn(String message) { public void warn(String message) {
err.println(Ansi.yellow("Warning: ") + message); err.println(Ansi.yellow("Warning: ") + message);
} }
@@ -0,0 +1,73 @@
package io.floci.cli.unit;
import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
/**
* AGENTS.md: every {@code printer.error(...)} ends with a suggested next step. A call that writes
* its own text must either put a second line in it or pass the next step as a second argument;
* a call that only forwards a message (a variable or {@code e.getMessage()}) is trusted to forward
* one that already has it. {@code e.withNextStep(...)} on a DockerException is the third way: the
* exception knows whether its text is docker's raw output or already carries advice.
*/
class ErrorHintConventionTest {
@Test
void everyErrorWithItsOwnTextEndsWithANextStep() throws Exception {
List<String> missing = new ArrayList<>();
try (Stream<Path> files = Files.walk(Path.of("src/main/java"))) {
for (Path file : files.filter(p -> p.toString().endsWith(".java")).toList()) {
String src = Files.readString(file);
int at = 0;
while ((at = src.indexOf("printer.error(", at)) >= 0) {
int start = at + "printer.error(".length();
String args = argumentsFrom(src, start);
if (args.contains("\"") && !args.contains("\\n") && !hasTopLevelComma(args)
&& !args.contains(".withNextStep(")) {
int line = (int) src.substring(0, at).chars().filter(c -> c == '\n').count() + 1;
missing.add(file + ":" + line);
}
at = start;
}
}
}
assertEquals(List.of(), missing, "error messages without a next step");
}
// The text between the opening parenthesis at 'start' and its matching close, string-aware.
private static String argumentsFrom(String src, int start) {
int depth = 1;
int i = start;
while (depth > 0) {
char c = src.charAt(i);
if (c == '"') {
i++;
while (src.charAt(i) != '"') i += src.charAt(i) == '\\' ? 2 : 1;
} else if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
}
i++;
}
return src.substring(start, i - 1);
}
private static boolean hasTopLevelComma(String args) {
String noStrings = args.replaceAll("\"(\\\\.|[^\"\\\\])*\"", "\"\"");
int depth = 0;
for (char c : noStrings.toCharArray()) {
if (c == '(') depth++;
else if (c == ')') depth--;
else if (c == ',' && depth == 0) return true;
}
return false;
}
}
@@ -0,0 +1,82 @@
package io.floci.cli.unit;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
import io.floci.cli.output.Ansi;
import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
class PrinterErrorTest {
private static String errorOf(String message, String nextStep) {
Ansi.disable();
ByteArrayOutputStream err = new ByteArrayOutputStream();
new Printer(new PrintStream(new ByteArrayOutputStream()), new PrintStream(err), OutputFormat.text, false)
.error(message, nextStep);
return err.toString().strip();
}
@Test
void theNextStepFollowsAOneLineMessage() {
assertEquals("Error: Failed to stop container: boom\nCheck Docker.",
errorOf("Failed to stop container: boom", "Check Docker."));
}
/** A message that already brings its own next step (a second line) is not given another. */
@Test
void aMessageWithItsOwnNextStepIsLeftAlone() {
assertEquals("Error: Timed out.\nRe-run it.", errorOf("Timed out.\nRe-run it.", "Check Docker."));
}
/** A trailing newline is not a second line, so the next step still follows. */
@Test
void aTrailingNewlineDoesNotHideTheNextStep() {
assertEquals("Error: Failed to stop container: boom\nCheck Docker.",
errorOf("Failed to stop container: boom\n", "Check Docker."));
}
/** Docker's own output never counts as advice, whether it ends in a newline or spans several lines. */
@Test
void dockersOwnOutputAlwaysGetsTheNextStep() {
assertEquals("Error response from daemon: boom\nCheck Docker.",
DockerException.ofOutput("Error response from daemon: boom\n").withNextStep("Check Docker."));
assertEquals("Error response from daemon: boom\nSee 'docker run --help'.\nCheck Docker.",
DockerException.ofOutput("Error response from daemon: boom\nSee 'docker run --help'.\n")
.withNextStep("Check Docker."));
}
/** An error in the CLI's own words that already says what to do is not given a second next step. */
@Test
void anErrorWithItsOwnAdviceKeepsIt() {
assertEquals("'docker stop' did not finish within 30s.\nCheck that the Docker daemon is responsive.",
new DockerException("'docker stop' did not finish within 30s.\nCheck that the Docker daemon is responsive.")
.withNextStep("Check Docker."));
assertEquals("Interrupted\nCheck Docker.", new DockerException("Interrupted").withNextStep("Check Docker."));
}
/** Through the real docker call: stderr ending in a newline reaches the user with the next step. */
@Test
@DisabledOnOs(OS.WINDOWS)
void aFailedDockerCallCarriesTheNextStep(@TempDir Path dir) throws Exception {
Path fakeDocker = dir.resolve("docker");
Files.writeString(fakeDocker, "#!/bin/sh\necho 'Error response from daemon: cannot stop container' >&2\nexit 1\n");
assertTrue(fakeDocker.toFile().setExecutable(true));
DockerException e = assertThrows(DockerException.class,
() -> new DockerClient(fakeDocker.toString()).stopContainer("floci", 1));
assertEquals("Error response from daemon: cannot stop container\n" + DockerClient.CHECK_DOCKER,
e.withNextStep(DockerClient.CHECK_DOCKER));
}
}
@@ -103,4 +103,16 @@ class SnapshotCommandsTest {
assertTrue(r[2].contains("Snapshot API not available"), r[2]); assertTrue(r[2].contains("Snapshot API not available"), r[2]);
} }
/** The hint has to check the instance that failed, not the default one. */
@ParameterizedTest
@CsvSource({"list,", "delete, nightly", "save, nightly", "load, nightly"})
void aFailedSnapshotCallPointsAtTheSameInstance(String command, String name) {
status = 500;
String[] r = name == null ? run("snapshot", command) : run("snapshot", command, name);
assertEquals("1", r[0]);
assertTrue(r[2].contains("floci status --container floci-snapshot-test-none"), r[2]);
}
} }