Skip to content

Commit 183de9f

Browse files
committed
invert condition to restore type narrowing, extract error templating
1 parent 7cc71ac commit 183de9f

File tree

1 file changed

+30
-25
lines changed

1 file changed

+30
-25
lines changed

src/core/Action.ts

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@ import {
1414
import type Ros from "./Ros.ts";
1515
import { v4 as uuidv4 } from "uuid";
1616

17+
class GoalError extends Error {
18+
override name = "GoalError";
19+
constructor(status: GoalStatus, errorValue?: string) {
20+
super(`${makeErrorMessage(status)}${errorValue ? `: ${errorValue}` : ""}`);
21+
}
22+
}
23+
24+
function makeErrorMessage(status: GoalStatus) {
25+
switch (status) {
26+
case GoalStatus.STATUS_CANCELED:
27+
return `Action was canceled`;
28+
case GoalStatus.STATUS_ABORTED:
29+
return `Action was aborted`;
30+
case GoalStatus.STATUS_CANCELING:
31+
return `Action is canceling`;
32+
case GoalStatus.STATUS_UNKNOWN:
33+
return `Action status unknown`;
34+
default:
35+
return `Action failed with status ${String(status)}`;
36+
}
37+
}
38+
1739
/**
1840
* A ROS 2 action client.
1941
*/
@@ -73,32 +95,15 @@ export default class Action<
7395
if (isRosbridgeActionResultMessage<TResult>(message)) {
7496
const status = message.status as GoalStatus;
7597

76-
// Check status code instead of result field to properly handle STATUS_CANCELED
77-
if (status === GoalStatus.STATUS_SUCCEEDED && message.result) {
78-
resultCallback(message.values);
98+
if (!message.result) {
99+
failedCallback(String(new GoalError(status, message.values)));
100+
} else if (status !== GoalStatus.STATUS_SUCCEEDED) {
101+
failedCallback(
102+
String(new GoalError(status, JSON.stringify(message.values))),
103+
);
104+
// Check status code instead of result field to properly handle STATUS_CANCELED
79105
} else {
80-
const baseError =
81-
typeof message.values === "string" ? message.values : "";
82-
83-
let errorMessage: string;
84-
switch (status) {
85-
case GoalStatus.STATUS_CANCELED:
86-
errorMessage = `Action was canceled${baseError ? `: ${baseError}` : ""}`;
87-
break;
88-
case GoalStatus.STATUS_ABORTED:
89-
errorMessage = `Action was aborted${baseError ? `: ${baseError}` : ""}`;
90-
break;
91-
case GoalStatus.STATUS_CANCELING:
92-
errorMessage = `Action is canceling${baseError ? `: ${baseError}` : ""}`;
93-
break;
94-
case GoalStatus.STATUS_UNKNOWN:
95-
errorMessage = `Action status unknown${baseError ? `: ${baseError}` : ""}`;
96-
break;
97-
default:
98-
errorMessage = `Action failed with status ${String(status)}${baseError ? `: ${baseError}` : ""}`;
99-
}
100-
101-
failedCallback(errorMessage);
106+
resultCallback(message.values);
102107
}
103108
} else if (isRosbridgeActionFeedbackMessage<TFeedback>(message)) {
104109
feedbackCallback?.(message.values);

0 commit comments

Comments
 (0)