[wpilibj] Fix incorrect robot name in reported error (#8294)

This commit is contained in:
Gold856
2026-06-23 13:45:24 -04:00
committed by GitHub
parent 38f113ae4b
commit de961b2b7e
2 changed files with 45 additions and 4 deletions

View File

@@ -303,6 +303,31 @@ public abstract class RobotBase implements AutoCloseable {
return robot;
}
/**
* Gets the Robot subclass name from a stack trace.
*
* @param elements The stack trace elements to walk.
* @return The Robot subclass name.
*/
protected static String getRobotName(StackTraceElement[] elements) {
// Walk bottom to top to account for multiple layers of subclassing
for (int i = elements.length - 1; i >= 0; i--) {
StackTraceElement element = elements[i];
try {
// Skip our own class when walking
if (RobotBase.class.equals(Class.forName(element.getClassName()))) {
continue;
}
if (RobotBase.class.isAssignableFrom(Class.forName(element.getClassName()))) {
return element.getClassName();
}
} catch (ClassNotFoundException e) {
// Unreachable
}
}
return "Unknown";
}
/** Run the robot main loop. */
@SuppressWarnings("PMD.AvoidCatchingGenericException")
private static <T extends RobotBase> void runRobot(Class<T> robotClass) {
@@ -316,11 +341,8 @@ public abstract class RobotBase implements AutoCloseable {
if (cause != null) {
throwable = cause;
}
String robotName = "Unknown";
StackTraceElement[] elements = throwable.getStackTrace();
if (elements.length > 0) {
robotName = elements[0].getClassName();
}
String robotName = getRobotName(elements);
DriverStationErrors.reportError(
"Unhandled exception instantiating robot " + robotName + " " + throwable, elements);
DriverStationErrors.reportError(

View File

@@ -130,6 +130,25 @@ class TimedRobotTest {
SimHooks.resumeTiming();
}
@Test
void robotNameTest() {
// Simulated stack trace from a robot crash
StackTraceElement[] elements = {
new StackTraceElement("org.wpilib.framework.TimedRobot", "<init>", null, 1),
new StackTraceElement("org.wpilib.framework.TimedRobotTest$MockRobot", "<init>", null, 1),
new StackTraceElement(
"jdk.internal.reflect.DirectConstructorHandleAccessor", "newInstance", null, 1),
new StackTraceElement("java.lang.reflect.Constructor", "newInstanceWithCaller", null, 1),
new StackTraceElement("java.lang.reflect.Constructor", "newInstance", null, 1),
new StackTraceElement("org.wpilib.util.ConstructorMatch", "newInstance", null, 1),
new StackTraceElement("org.wpilib.framework.RobotBase", "constructRobot", null, 1),
new StackTraceElement("org.wpilib.framework.RobotBase", "runRobot", null, 1),
new StackTraceElement("org.wpilib.framework.RobotBase", "lambda$startRobot$0", null, 1),
new StackTraceElement("java.lang.Thread", "run", null, 1)
};
assertEquals("org.wpilib.framework.TimedRobotTest$MockRobot", MockRobot.getRobotName(elements));
}
@Test
@ResourceLock("timing")
void disabledModeTest() {