Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
87fe2a5
fix: standardize error handling and improve resilience across SDK
Jul 15, 2026
4054ef5
fix: prevent NPE, empty error messages, and swallowed InterruptedExce…
Jul 15, 2026
8952eb9
fix: resolve incorrect statusCode when HTTP 200 with body error
Jul 16, 2026
0640a05
fix: resolve incorrect statusCode when HTTP 200 with body error
Jul 16, 2026
f8a4bb8
refactor: standardize error handling with PublicErrorDef
Jul 21, 2026
88f3ed6
fix: resolve NPE in WebSocket message handling causing test hang
Jul 21, 2026
dbee28b
fix: resolve NPE in WebSocket message handling causing test hang
Jul 21, 2026
36905cb
refactor: standardize error handling with PublicErrorDef
Jul 23, 2026
4325d60
fix: standardize error handling with proper status codes and structur…
Jul 27, 2026
a8f01a1
Merge branch 'main' into dev/errors
lzsweb Jul 27, 2026
ed47ae6
fix: add missing fromErrorCode static lookup method to PublicErrorDef
Jul 27, 2026
01eef2d
feat: unify agentstudio error codes onto PublicErrorDef registry
foleydang Jul 28, 2026
d4b8af4
style: apply google-java-format to agentstudio error files
foleydang Jul 28, 2026
e0d435a
fix(websocket): improve error handling in OkHttpWebSocketClient
Aug 3, 2026
23751aa
refactor: rename PublicErrorDef to ClientErrorDef
Aug 5, 2026
b5fc7d3
Merge branch 'main' into dev/errors
lzsweb Aug 6, 2026
82406a9
refactor(errors): introduce two-layer error code system
Aug 6, 2026
ec195f8
refactor(errors): introduce two-layer error code system
Aug 6, 2026
056500d
refactor: scope agentstudio internal error codes to public-taxonomy gaps
foleydang Aug 7, 2026
87d0143
refactor: drop the Kind enum, table-drive per-status error codes
foleydang Aug 7, 2026
c7538d4
refactor: split AgentStudioException by error path, drop status guessing
foleydang Aug 7, 2026
6554da8
refactor: split AgentStudioException by error path, drop status guessing
foleydang Aug 7, 2026
a3b9a2b
Merge remote-tracking branch 'origin/dev/errors' into dev/errors
Aug 10, 2026
ff94958
Merge remote-tracking branch 'origin/main' into dev/errors
Aug 19, 2026
7683bb6
fix(protocol/websocket): keep fixed status code 44 after merging main
Aug 19, 2026
eedf681
feat(protocol/websocket): report 503 SERVICE_UNAVAILABLE on exhausted…
Aug 19, 2026
fca6672
Merge remote-tracking branch 'origin/dev/errors' into dev/errors
Aug 20, 2026
6d822fe
feat(errors): enhance error handling system with comprehensive error …
Aug 20, 2026
ad8920a
refactor(errors): remove hardcoded URLs and fix line length
Aug 20, 2026
431864c
feat: replace vague descriptions with specific URLs in error solutions
Aug 21, 2026
35bc973
refactor(errors): rename InternalErrorCode to SdkErrorCode
Aug 31, 2026
c9176e0
refactor(errors): rename InternalErrorCode to SdkErrorCode
Aug 31, 2026
05238f6
fix(errors): revive timeout tests and drop error-code leftovers
Sep 11, 2026
9672041
Merge branch 'main' into dev/errors
Sep 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,23 @@ private static ApiException wrapFailure(Throwable t, Response response) {
} catch (IOException e) {
log.debug("Failed to read SSE failure response body", e);
}
Status status =
Status.builder()
.statusCode(code)
.code(code >= 500 ? "server_error" : code == 401 ? "auth_error" : "http_error")
.message(body.isEmpty() ? "HTTP " + code : body)
.build();

// Try to extract original error code and message from response body
String apiCode = "";
String apiMessage = body.isEmpty() ? response.message() : body;
try {
com.google.gson.JsonObject json = com.alibaba.dashscope.utils.JsonUtils.parse(body);
if (json.has("code")) {
apiCode = json.get("code").getAsString();
}
if (json.has("message")) {
apiMessage = json.get("message").getAsString();
}
} catch (Exception e) {
log.debug("Failed to parse error response body as JSON", e);
}

Status status = Status.builder().statusCode(code).code(apiCode).message(apiMessage).build();
return new ApiException(status, t);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,10 @@ public void onResponse(Call call, Response response) {
if (!r.isSuccessful()) {
future.completeExceptionally(
new ApiException(
Status.builder().statusCode(r.code()).message(body).build()));
Status.builder()
.statusCode(r.code())
.message(body.isEmpty() ? r.message() : body)
.build()));
return;
}
future.complete(
Expand Down
63 changes: 59 additions & 4 deletions src/main/java/com/alibaba/dashscope/api/AsynchronousApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import com.alibaba.dashscope.base.HalfDuplexParamBase;
import com.alibaba.dashscope.common.DashScopeResult;
import com.alibaba.dashscope.common.ErrorType;
import com.alibaba.dashscope.common.Status;
import com.alibaba.dashscope.common.TaskStatus;
import com.alibaba.dashscope.exception.ApiException;
Expand All @@ -18,8 +19,10 @@
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
Comment thread
luk384090-cloud marked this conversation as resolved.

/** Support DashScope async task CRUD. */
@Slf4j
public final class AsynchronousApi<ParamT extends HalfDuplexParamBase> {
final HalfDuplexClient client;
ConnectionOptions connectionOptions;
Expand Down Expand Up @@ -104,6 +107,10 @@ public DashScopeResult wait(
int maxWaitMilliseconds = 5 * 1000;
int incrementSteps = 3;
int step = 0;
int transientErrorCount = 0;
final int MAX_TRANSIENT_ERRORS = 20;
int transientBackoffMs = 1000;
final int MAX_TRANSIENT_BACKOFF_MS = 10000;
long startTime = System.currentTimeMillis();
long timeoutMillis = timeoutSeconds > 0 ? timeoutSeconds * 1000L : -1L;
while (true) {
Expand All @@ -113,11 +120,11 @@ public DashScopeResult wait(
throw new ApiException(
Status.builder()
.statusCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT)
.code("TaskWaitTimeout")
.code(ErrorType.TASK_WAIT_TIMEOUT.getValue())
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.message(
StringUtils.format(
"Waiting for task [%s] timed out after %d ms (timeoutSeconds=%d).",
taskId, elapsed, timeoutSeconds))
"Waiting for task [%s] timed out after %d ms (timeoutSeconds=%d). Encountered %d transient errors (503/504) during polling.",
taskId, elapsed, timeoutSeconds, transientErrorCount))
.build());
}
}
Expand Down Expand Up @@ -155,14 +162,62 @@ public DashScopeResult wait(
}
try {
Thread.sleep(sleepMs);
} catch (InterruptedException ignored) {
} catch (InterruptedException e) {
Comment thread
luk384090-cloud marked this conversation as resolved.
Thread.currentThread().interrupt();
throw new ApiException(
Status.builder()
.statusCode(-1)
.code("Interrupted")
.message("Thread was interrupted while waiting for task.")
.build(),
e);
}
}
} catch (ApiException e) {
if (e.getStatus().getStatusCode() != HttpURLConnection.HTTP_UNAVAILABLE
&& e.getStatus().getStatusCode() != HttpURLConnection.HTTP_GATEWAY_TIMEOUT) {
throw e;
}
transientErrorCount++;
Comment thread
luk384090-cloud marked this conversation as resolved.
log.warn(
"Transient error during async task polling [taskId={}]: status={}, message={}, retry_count={}, backoff_ms={}",
taskId,
e.getStatus().getStatusCode(),
e.getMessage(),
transientErrorCount,
transientBackoffMs);
if (transientErrorCount >= MAX_TRANSIENT_ERRORS) {
throw new ApiException(
Status.builder()
.statusCode(e.getStatus().getStatusCode())
.code("TooManyTransientErrors")
.message(
StringUtils.format(
"Encountered %d transient errors (503/504) while waiting for task [%s]. The service may be experiencing issues. Last error: %s",
transientErrorCount, taskId, e.getMessage()))
.build());
}
long sleepMs = transientBackoffMs;
if (timeoutMillis > 0) {
long remaining = timeoutMillis - (System.currentTimeMillis() - startTime);
if (remaining <= 0) {
continue;
}
sleepMs = Math.min(sleepMs, remaining);
}
try {
Thread.sleep(sleepMs);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new ApiException(
Status.builder()
.statusCode(-1)
.code("Interrupted")
.message("Thread was interrupted while waiting for task.")
.build(),
ie);
}
Comment thread
luk384090-cloud marked this conversation as resolved.
transientBackoffMs = Math.min(transientBackoffMs * 2, MAX_TRANSIENT_BACKOFF_MS);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ public void onError(Exception e) {
Status timeoutStatus =
Status.builder()
.statusCode(408)
.code("RequestTimeOut")
.code(ErrorType.REQUEST_TIMEOUT.getValue())
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.message("Timeout waiting for audio data from server.")
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.build();
throw new ApiException(timeoutStatus);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,16 +352,22 @@ private void handleTaskFinished(JsonObject message) {
private void handleTaskFailed(JsonObject message) {
log.error("Task failed: " + message.toString());
if (callback != null) {
String errorMessage = "Unknown error";
if (message.has("header") && message.getAsJsonObject("header").has("error_message")) {
errorMessage = message.getAsJsonObject("header").get("error_message").getAsString();
String errorCode = "";
String errorMessage = "";
if (message.has("header")) {
JsonObject header = message.getAsJsonObject("header");
if (header.has("error_code")) {
errorCode = header.get("error_code").getAsString();
}
if (header.has("error_message")) {
errorMessage = header.get("error_message").getAsString();
}
}

// Create a Status object for the ApiException
com.alibaba.dashscope.common.Status status =
com.alibaba.dashscope.common.Status.builder()
.statusCode(-1)
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.code("TASK_FAILED")
.code(errorCode)
.message(errorMessage)
.build();
callback.onError(new ApiException(status));
Expand Down
66 changes: 66 additions & 0 deletions src/main/java/com/alibaba/dashscope/common/DashScopeResult.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ protected <T extends Result> T fromResponse(Protocol protocol, NetworkResponse r
// Set default empty string for successful responses
this.setMessage("");
}
if (this.getCode() != null && !this.getCode().isEmpty()) {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
int resolvedStatusCode =
resolveStatusCode(
this.getStatusCode(), response.getHttpStatusCode(), this.getCode());
throw new ApiException(
Status.builder()
.statusCode(resolvedStatusCode)
.code(this.getCode())
.message(this.getMessage())
.requestId(this.getRequestId())
.build());
}
}
if (jsonObject.has(ApiKeywords.PAYLOAD)) {
JsonObject payload = jsonObject.getAsJsonObject(ApiKeywords.PAYLOAD);
Expand Down Expand Up @@ -132,6 +144,17 @@ protected <T extends Result> T fromResponse(Protocol protocol, NetworkResponse r
// Set default empty string for successful responses
this.setMessage("");
}
if (this.getCode() != null && !this.getCode().isEmpty()) {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
int resolvedStatusCode =
resolveStatusCode(this.getStatusCode(), response.getHttpStatusCode(), this.getCode());
throw new ApiException(
Status.builder()
.statusCode(resolvedStatusCode)
.code(this.getCode())
.message(this.getMessage())
.requestId(this.getRequestId())
.build());
}
if (jsonObject.has(ApiKeywords.DATA)) {
if (jsonObject.has(ApiKeywords.REQUEST_ID)) {
jsonObject.remove(ApiKeywords.REQUEST_ID);
Expand Down Expand Up @@ -230,6 +253,17 @@ public <T extends Result> T fromResponse(
// Set default empty string for successful responses
this.setMessage("");
}
if (this.getCode() != null && !this.getCode().isEmpty()) {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
int resolvedStatusCode =
resolveStatusCode(this.getStatusCode(), response.getHttpStatusCode(), this.getCode());
throw new ApiException(
Status.builder()
.statusCode(resolvedStatusCode)
.code(this.getCode())
.message(this.getMessage())
.requestId(this.getRequestId())
.build());
}
if (jsonObject.has(ApiKeywords.DATA)) {
if (jsonObject.has(ApiKeywords.REQUEST_ID)) {
jsonObject.remove(ApiKeywords.REQUEST_ID);
Expand All @@ -256,4 +290,36 @@ private Map<String, Object> changeHeaders(Map<String, List<String>> headers) {
(v1, v2) -> v1,
java.util.LinkedHashMap::new));
}

/**
* Resolve the appropriate HTTP status code for an API exception. Priority: 1) Body status_code,
* 2) HTTP response status code, 3) Infer from error code.
*/
private int resolveStatusCode(Integer bodyStatusCode, Integer httpStatusCode, String errorCode) {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
if (bodyStatusCode != null && bodyStatusCode != 200) {
return bodyStatusCode;
}
if (httpStatusCode != null && httpStatusCode != 200) {
return httpStatusCode;
}
// Infer status code from business error code when both are 200 or null
if (errorCode != null) {
if (errorCode.contains("InvalidParameter") || errorCode.contains("BadRequest")) {
return 400;
} else if (errorCode.contains("Unauthorized") || errorCode.contains("ApiKey")) {
return 401;
} else if (errorCode.contains("Forbidden") || errorCode.contains("AccessDenied")) {
return 403;
} else if (errorCode.contains("NotFound")) {
return 404;
} else if (errorCode.contains("Throttling") || errorCode.contains("RateLimit")) {
return 429;
} else if (errorCode.contains("InternalError") || errorCode.contains("SystemError")) {
return 500;
}
}
return bodyStatusCode != null
? bodyStatusCode
: (httpStatusCode != null ? httpStatusCode : 200);
}
}
26 changes: 15 additions & 11 deletions src/main/java/com/alibaba/dashscope/common/ErrorType.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,26 @@

public enum ErrorType {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated

/** The error happens in the response body. */
RESPONSE_ERROR("response_error"),
/** Network error: DNS failure, connection refused, etc. API did not respond. */
NETWORK_ERROR("network error"),

/** The error happens because the request is canceled. */
REQUEST_CANCELLED("request_cancelled"),
/** WebSocket connection failed after retries. API returned no content. */
CONNECTION_ERROR("ConnectionError"),

/** The error happens because the network protocol is not supported. */
PROTOCOL_UNSUPPORTED("protocol_unsupported"),
/** Asynchronous task polling timed out. API is still processing. */
TASK_WAIT_TIMEOUT("TaskWaitTimeout"),

/** The api key is not correct. */
API_KEY_ERROR("api_key_error"),
/** HTTP TTS waiting for audio data timed out. API returned no error. */
REQUEST_TIMEOUT("RequestTimeOut"),

/** An unknown error. */
UNKNOWN_ERROR("unknown_error"),
/** JSON parsing failed. Original body preserved in message field. */
JSON_PARSE_ERROR("json_parse_error"),

NETWORK_ERROR("network error"),
/** Failed to read response body due to IOException. HTTP status code preserved. */
BODY_READ_ERROR("body_read_error"),

/** Non-JSON content type received (e.g., HTML error page). Original body in message. */
NON_JSON_RESPONSE("non_json_response"),
;

private final String value;
Expand Down
Loading
Loading