Skip to content
Open
Show file tree
Hide file tree
Changes from 15 commits
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
@@ -0,0 +1,214 @@
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.agentstudio;

import com.alibaba.dashscope.common.ClientErrorDef;
import com.alibaba.dashscope.common.Status;
import com.alibaba.dashscope.exception.ApiException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
* Typed AgentStudio error. Codes converge onto {@link ClientErrorDef} (shared with the Python SDK):
* {@link #getCode()} is the unified Anthropic-compatible code, the raw server code is on {@link
* #getRawCode()}, and {@link #getKind()} branches on the error category. Extends {@link
* ApiException} so existing {@code catch (ApiException)} still works.
*/
public class AgentStudioException extends ApiException {

public enum Kind {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
INVALID_REQUEST,
AUTHENTICATION,
PERMISSION_DENIED,
NOT_FOUND,
CONFLICT,
RATE_LIMIT,
SERVER_ERROR,
NETWORK,
UNKNOWN
}

private final Kind kind;
private final String code;
private final String errorMessage;

private AgentStudioException(
Status status, Kind kind, String code, String errorMessage, Throwable cause) {
super(status, cause);
this.kind = kind;
this.code = code;
this.errorMessage = errorMessage;
}

public Kind getKind() {
return kind;
}

public int getStatusCode() {
return getStatus() != null ? getStatus().getStatusCode() : -1;
}

/** Unified error code from the Anthropic-compatible taxonomy (e.g. {@code not_found_error}). */
public String getCode() {
return code;
}

/** Raw server-supplied code before normalization (may be {@code null} or empty). */
public String getRawCode() {
return getStatus() != null ? getStatus().getCode() : null;
}

/** Resolved message: the server's text when present, else the registry default. */
public String getErrorMessage() {
return errorMessage;
}

public String getRequestId() {
return getStatus() != null ? getStatus().getRequestId() : null;
}

public boolean isRetryable() {
return isRetryable(getStatusCode());
}

/** A -1 status code marks a network-level failure (no HTTP response). */
public static boolean isRetryable(int statusCode) {
return statusCode == -1
|| statusCode == 408
|| statusCode == 409
|| statusCode == 429
|| statusCode >= 500;
}

public static Kind classify(int statusCode) {
if (statusCode == -1) {
return Kind.NETWORK;
}
switch (statusCode) {
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
case 400:
return Kind.INVALID_REQUEST;
case 401:
return Kind.AUTHENTICATION;
case 403:
return Kind.PERMISSION_DENIED;
case 404:
return Kind.NOT_FOUND;
case 409:
return Kind.CONFLICT;
case 429:
return Kind.RATE_LIMIT;
default:
return statusCode >= 500 ? Kind.SERVER_ERROR : Kind.UNKNOWN;
}
}

public static AgentStudioException wrap(ApiException e) {
if (e instanceof AgentStudioException) {
return (AgentStudioException) e;
}
Status status = e.getStatus();
if (status == null) {
status = Status.builder().statusCode(-1).build();
}
int statusCode = status.getStatusCode();
String unifiedCode = unifyCode(statusCode, status.getCode());
String message = resolveMessage(statusCode, status.getMessage());
return new AgentStudioException(
status, classify(statusCode), unifiedCode, message, e.getCause());
}

@Override
public String getMessage() {
return String.format(
"[%s] status=%d code=%s message=%s request_id=%s",
kind, getStatusCode(), code, errorMessage, getRequestId());
}

// --- Normalization (mirrors dashscope/agentstudio/exceptions.py) ---

private static final Map<Integer, ClientErrorDef> STATUS_TO_PUBLIC = new HashMap<>();
private static final Set<String> REGISTRY_ANTHROPIC_CODES = new HashSet<>();
private static final Map<String, String> LEGACY_CODE_ALIASES = new HashMap<>();
private static final Map<Kind, String> KIND_TO_CODE = new HashMap<>();
private static final Pattern PLACEHOLDER = Pattern.compile("\\s*:?\\s*\\{[^}]+\\}");

static {
Comment thread
foleydang marked this conversation as resolved.
STATUS_TO_PUBLIC.put(400, ClientErrorDef.INVALID_REQUEST);
STATUS_TO_PUBLIC.put(401, ClientErrorDef.AUTH_FAILED);
STATUS_TO_PUBLIC.put(403, ClientErrorDef.PERMISSION_DENIED);
STATUS_TO_PUBLIC.put(404, ClientErrorDef.RESOURCE_NOT_FOUND);
STATUS_TO_PUBLIC.put(429, ClientErrorDef.RATE_LIMIT_EXCEEDED);
STATUS_TO_PUBLIC.put(500, ClientErrorDef.INTERNAL_ERROR);
STATUS_TO_PUBLIC.put(502, ClientErrorDef.INTERNAL_ERROR);
STATUS_TO_PUBLIC.put(503, ClientErrorDef.SERVICE_UNAVAILABLE);
STATUS_TO_PUBLIC.put(504, ClientErrorDef.REQUEST_TIMEOUT);

for (ClientErrorDef def : ClientErrorDef.values()) {
REGISTRY_ANTHROPIC_CODES.add(def.getAnthropicErrorCode());
}

LEGACY_CODE_ALIASES.put("permission_denied_error", "permission_error"); // TODO(bma-fix)

KIND_TO_CODE.put(Kind.INVALID_REQUEST, "invalid_request_error");
Comment thread
luk384090-cloud marked this conversation as resolved.
Outdated
KIND_TO_CODE.put(Kind.AUTHENTICATION, "authentication_error");
KIND_TO_CODE.put(Kind.PERMISSION_DENIED, "permission_error");
KIND_TO_CODE.put(Kind.NOT_FOUND, "not_found_error");
KIND_TO_CODE.put(Kind.CONFLICT, "conflict_error");
KIND_TO_CODE.put(Kind.RATE_LIMIT, "rate_limit_error");
KIND_TO_CODE.put(Kind.SERVER_ERROR, "api_error");
KIND_TO_CODE.put(Kind.NETWORK, "api_connection_error");
KIND_TO_CODE.put(Kind.UNKNOWN, "api_status_error");
}

/**
* Resolve the unified code: a recognized server code wins, else the per-status registry row, else
* the kind default.
*/
static String unifyCode(int statusCode, String serverCode) {
String normalized = normalizeServerCode(serverCode);
if (normalized != null) {
return normalized;
}
ClientErrorDef pub = STATUS_TO_PUBLIC.get(statusCode);
if (pub != null) {
return pub.getAnthropicErrorCode();
}
return KIND_TO_CODE.get(classify(statusCode));
}

private static String normalizeServerCode(String code) {
if (code == null || code.isEmpty()) {
return null;
}
if (LEGACY_CODE_ALIASES.containsKey(code)) {
return LEGACY_CODE_ALIASES.get(code);
}
if (REGISTRY_ANTHROPIC_CODES.contains(code)) {
return code; // already a unified Anthropic code
}
ClientErrorDef byErrorCode = ClientErrorDef.fromErrorCode(code);
if (byErrorCode != null) {
return byErrorCode.getAnthropicErrorCode(); // e.g. "NotFoundError" -> "not_found_error"
}
return null;
}

static String resolveMessage(int statusCode, String serverMessage) {
if (serverMessage != null && !serverMessage.isEmpty()) {
return serverMessage;
}
ClientErrorDef pub = STATUS_TO_PUBLIC.get(statusCode);
return pub != null ? defaultMessage(pub) : "HTTP " + statusCode;
}

/** Default message with unresolved {@code {var}} placeholders stripped. */
private static String defaultMessage(ClientErrorDef pub) {
String msg = PLACEHOLDER.matcher(pub.getErrorMsg()).replaceAll("").trim();
if (!msg.isEmpty() && !msg.endsWith(".")) {
msg += ".";
}
return msg;
}
}
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
@@ -1,6 +1,7 @@
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.agentstudio.resource;

import com.alibaba.dashscope.agentstudio.AgentStudioException;
import com.alibaba.dashscope.api.GeneralApi;
import com.alibaba.dashscope.base.HalfDuplexParamBase;
import com.alibaba.dashscope.common.DashScopeResult;
Expand Down Expand Up @@ -32,15 +33,20 @@ public void onComplete() {}

@Override
public void onError(Exception e) {
future.completeExceptionally(e);
future.completeExceptionally(normalize(e));
}
});
} catch (Exception e) {
future.completeExceptionally(e);
future.completeExceptionally(normalize(e));
}
return future;
}

/** Wrap {@link ApiException}s as the unified {@link AgentStudioException}. */
private static Throwable normalize(Throwable e) {
return e instanceof ApiException ? AgentStudioException.wrap((ApiException) e) : e;
}

static <T> CompletableFuture<T> failedFuture(Throwable ex) {
CompletableFuture<T> f = new CompletableFuture<>();
f.completeExceptionally(ex);
Expand All @@ -52,9 +58,6 @@ static <T> T joinAndUnwrap(CompletableFuture<T> future) {
return future.join();
} catch (CompletionException e) {
Throwable cause = e.getCause();
if (cause instanceof ApiException) {
throw (ApiException) cause;
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
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
Loading