Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
32 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
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;
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
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
45 changes: 42 additions & 3 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 @@ -163,6 +170,38 @@ public DashScopeResult wait(
&& 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 ignored) {
}
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
27 changes: 27 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,15 @@ 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
throw new ApiException(
Status.builder()
.statusCode(this.getStatusCode())
.code(this.getCode())
.message(this.getMessage())
.requestId(this.getRequestId())
.build());
}
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
}
if (jsonObject.has(ApiKeywords.PAYLOAD)) {
JsonObject payload = jsonObject.getAsJsonObject(ApiKeywords.PAYLOAD);
Expand Down Expand Up @@ -132,6 +141,15 @@ 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
throw new ApiException(
Status.builder()
.statusCode(this.getStatusCode())
.code(this.getCode())
.message(this.getMessage())
.requestId(this.getRequestId())
.build());
}
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
if (jsonObject.has(ApiKeywords.DATA)) {
if (jsonObject.has(ApiKeywords.REQUEST_ID)) {
jsonObject.remove(ApiKeywords.REQUEST_ID);
Expand Down Expand Up @@ -230,6 +248,15 @@ 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
throw new ApiException(
Status.builder()
.statusCode(this.getStatusCode())
.code(this.getCode())
.message(this.getMessage())
.requestId(this.getRequestId())
.build());
}
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
if (jsonObject.has(ApiKeywords.DATA)) {
if (jsonObject.has(ApiKeywords.REQUEST_ID)) {
jsonObject.remove(ApiKeywords.REQUEST_ID);
Expand Down
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.

/** 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
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public final class OkHttpHttpClient implements HalfDuplexClient {
private static final MediaType MEDIA_TYPE_APPLICATION_JSON =
MediaType.parse("application/json; charset=utf-8");

private Status parseStreamEventData(String data) {
private Status parseStreamEventData(String data, int httpStatusCode) {
try {
JsonObject jsonResponse = JsonUtils.parse(data);
String code = "";
Expand All @@ -69,16 +69,16 @@ private Status parseStreamEventData(String data) {
message = jsonResponse.get(ApiKeywords.MESSAGE).getAsString();
}
return Status.builder()
.statusCode(400)
.statusCode(httpStatusCode)
.code(code)
.message(message)
.requestId(requestId)
.isJson(true)
.build();
} catch (Throwable e) {
return Status.builder()
.statusCode(400)
.code(ErrorType.RESPONSE_ERROR.getValue())
.statusCode(httpStatusCode)
.code("")
Comment thread
luk384090-cloud marked this conversation as resolved.
.message(data)
.isJson(false)
.build();
Expand Down Expand Up @@ -108,11 +108,26 @@ private Status parseFailedJson(int statusCode, String body) {
.isJson(true)
.build();
} catch (Throwable e) {
// Try to extract code/message even if standard parsing failed
String extractedCode = "";
String extractedMessage = body;
try {
JsonObject json = JsonUtils.parse(body);
if (json.has(ApiKeywords.CODE)) {
extractedCode = json.get(ApiKeywords.CODE).getAsString();
}
if (json.has(ApiKeywords.MESSAGE)) {
extractedMessage = json.get(ApiKeywords.MESSAGE).getAsString();
}
} catch (Exception ex) {
// Parsing failed, use defaults
}

return Status.builder()
.statusCode(statusCode)
.code(ErrorType.RESPONSE_ERROR.getValue())
.message(body)
.isJson(true)
.code(extractedCode.isEmpty() ? "" : extractedCode)
.message(extractedMessage)
.isJson(!extractedCode.isEmpty())
.build();
}
}
Expand All @@ -137,9 +152,9 @@ private Status parseFailed(Response response, Throwable th) {
} catch (IOException e) {
return Status.builder()
.statusCode(response.code())
.code(ErrorType.RESPONSE_ERROR.getValue())
.message("Failed read response body: " + e.getMessage())
.isJson(true)
.code("")
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.message("[SDK] Failed to read response body: " + e.getMessage())
.isJson(false)
.build();
}
return parseFailedJson(response.code(), body);
Expand All @@ -155,24 +170,47 @@ private Status parseFailed(Response response, Throwable th) {
}
return Status.builder()
.statusCode(response.code())
.code(ErrorType.RESPONSE_ERROR.getValue())
.code("")
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.message(body)
.isJson(false)
.build();
} catch (IOException e) {
return Status.builder()
.statusCode(response.code())
.code(ErrorType.RESPONSE_ERROR.getValue())
.message("Failed read response body: " + e.getMessage())
.isJson(true)
.code("")
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
.message("[SDK] Failed to read SSE response body: " + e.getMessage())
.isJson(false)
.build();
}
} else {
String body = "";
try {
body = response.body().string();
} catch (IOException e) {
log.debug("Failed to read non-JSON response body", e);
}

// Try to extract code/message from body even if Content-Type is not application/json
String extractedCode = "";
String extractedMessage = body.isEmpty() ? response.message() : body;

try {
JsonObject json = JsonUtils.parse(body);
if (json.has(ApiKeywords.CODE)) {
extractedCode = json.get(ApiKeywords.CODE).getAsString();
}
if (json.has(ApiKeywords.MESSAGE)) {
extractedMessage = json.get(ApiKeywords.MESSAGE).getAsString();
}
} catch (Exception ex) {
// Parsing failed, use defaults
}

return Status.builder()
.statusCode(response.code())
.code(ErrorType.RESPONSE_ERROR.getValue())
.message(response.message())
.isJson(false)
.code(extractedCode.isEmpty() ? "" : extractedCode)
.message(extractedMessage)
.isJson(!extractedCode.isEmpty())
.build();
}
}
Expand Down Expand Up @@ -255,6 +293,10 @@ public DashScopeResult send(HalfDuplexRequest req) throws NoApiKeyException, Api
.build(),
req.getIsFlatten(),
req);
} catch (ApiException e) {
throw e;
} catch (NoApiKeyException e) {
throw e;
} catch (Throwable e) {
throw new ApiException(e);
}
Expand Down Expand Up @@ -308,7 +350,7 @@ private void handleSSEEvent(
HalfDuplexRequest req) {
log.debug(StringUtils.format("Event: id %s, type: %s, data: %s", id, eventType, data));
if (SSEEventType.ERROR.equals(eventType)) {
Status st = parseStreamEventData(data);
Status st = parseStreamEventData(data, response.code());
emitter.onError(new ApiException(st));
} else if (SSEEventType.DATA.equals(eventType) || SSEEventType.RESULT.equals(eventType)) {
emitter.onNext(
Expand Down Expand Up @@ -453,7 +495,7 @@ public void onEvent(
java.lang.String data) {
log.debug(StringUtils.format("Event: id %s, type: %s, data: %s", id, type, data));
if (SSEEventType.ERROR.equals(type)) {
Status st = parseStreamEventData(data);
Status st = parseStreamEventData(data, response.code());
callback.onError(new ApiException(st));
} else if (SSEEventType.DATA.equals(type) || SSEEventType.RESULT.equals(type)) {
callback.onEvent(
Expand Down
Loading
Loading