Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -54,6 +54,7 @@ import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
{{#jsr310}}
Expand Down Expand Up @@ -1196,6 +1197,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
* @param authNames The authentications to apply
* @param returnType The return type into which to deserialize the response
* @param isBodyNullable True if the body is nullable
* @param errorTypes Mapping of error codes to types into which to deserialize the response
* @return The response body in type of string
* @throws ApiException API exception
*/
Expand All @@ -1212,7 +1214,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
String contentType,
String[] authNames,
GenericType<T> returnType,
boolean isBodyNullable)
boolean isBodyNullable,
Map<String, GenericType> errorTypes
)
throws ApiException {

String targetURL;
Expand All @@ -1223,7 +1227,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
if (index < 0 || index >= serverConfigurations.size()) {
throw new ArrayIndexOutOfBoundsException(
String.format(
java.util.Locale.ROOT,
Locale.ROOT,
"Invalid index %d when selecting the host settings. Must be less than %d",
index, serverConfigurations.size()));
}
Expand Down Expand Up @@ -1333,14 +1337,16 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
String respBody = null;
if (response.hasEntity()) {
try {
// call bufferEntity, so that a subsequent call to `readEntity` in `deserialize` doesn't fail
response.bufferEntity();
respBody = String.valueOf(response.readEntity(String.class));
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatus(), message, buildResponseHeaders(response), respBody);
response.getStatus(), message, buildResponseHeaders(response), respBody, deserializeErrorEntity(errorTypes, response));
}
} finally {
try {
Expand All @@ -1351,6 +1357,30 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
}
}
}

/**
* Deserialize the response body into an error entity based on HTTP status code.
* Looks up the error type from the errorTypes map using the response status code,
* or falls back to the "default" error type if no match is found.
*
* @param errorTypes Map of status code strings to GenericType for deserialization
* @param response The HTTP response
* @return The deserialized error entity, or null if not found or deserialization fails
*/
private Object deserializeErrorEntity(Map<String, GenericType> errorTypes, Response response) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add a docstring explaining what this function does

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

if (errorTypes == null) {
return null;
}
GenericType errorType = errorTypes.get(String.valueOf(response.getStatus()));
if (errorType == null) {
errorType = errorTypes.get("0"); // "0" is the "default" response
}
try {
return deserialize(response, errorType);
} catch (Exception e) {
return null;
}
}

protected Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity<?> entity) {
Response response;
Expand All @@ -1377,7 +1407,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
*/
@Deprecated
public <T> ApiResponse<T> invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType, boolean isBodyNullable) throws ApiException {
return invokeAPI(null, path, method, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType, isBodyNullable);
return invokeAPI(null, path, method, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType, isBodyNullable, null/*TODO SME manage*/);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,20 @@ public class {{classname}} {
{{#hasAuthMethods}}
String[] localVarAuthNames = {{=% %=}}new String[] {%#authMethods%"%name%"%^-last%, %/-last%%/authMethods%};%={{ }}=%
{{/hasAuthMethods}}
final Map<String, GenericType> localVarErrorTypes = new HashMap<String, GenericType>();
{{#responses}}
{{^-first}}
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Apr 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Error-type map population skips the first response unconditionally, which can omit a valid error/default schema and break ApiException error deserialization.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache, line 200:

<comment>Error-type map population skips the first response unconditionally, which can omit a valid error/default schema and break ApiException error deserialization.</comment>

<file context>
@@ -195,12 +195,20 @@ public class {{classname}} {
     {{/hasAuthMethods}}
+    final Map<String, GenericType> localVarErrorTypes = new HashMap<String, GenericType>();
+    {{#responses}}
+    {{^-first}}
+    {{#dataType}}
+    localVarErrorTypes.put("{{code}}", new GenericType<{{{dataType}}}>() {});
</file context>
Fix with Cubic

{{#dataType}}
localVarErrorTypes.put("{{code}}", new GenericType<{{{dataType}}}>() {});
{{/dataType}}
{{/-first}}
{{/responses}}
{{#returnType}}
GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {};
{{/returnType}}
return apiClient.invokeAPI("{{classname}}.{{operationId}}", {{#hasPathParams}}localVarPath{{/hasPathParams}}{{^hasPathParams}}"{{{path}}}"{{/hasPathParams}}, "{{httpMethod}}", {{#queryParams}}{{#-first}}localVarQueryParams{{/-first}}{{/queryParams}}{{^queryParams}}new ArrayList<>(){{/queryParams}}, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}},
{{#headerParams}}{{#-first}}localVarHeaderParams{{/-first}}{{/headerParams}}{{^headerParams}}new LinkedHashMap<>(){{/headerParams}}, {{#cookieParams}}{{#-first}}localVarCookieParams{{/-first}}{{/cookieParams}}{{^cookieParams}}new LinkedHashMap<>(){{/cookieParams}}, {{#formParams}}{{#-first}}localVarFormParams{{/-first}}{{/formParams}}{{^formParams}}new LinkedHashMap<>(){{/formParams}}, localVarAccept, localVarContentType,
{{#hasAuthMethods}}localVarAuthNames{{/hasAuthMethods}}{{^hasAuthMethods}}null{{/hasAuthMethods}}, {{#returnType}}localVarReturnType{{/returnType}}{{^returnType}}null{{/returnType}}, {{#bodyParam}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/bodyParam}}{{^bodyParam}}false{{/bodyParam}});
{{#hasAuthMethods}}localVarAuthNames{{/hasAuthMethods}}{{^hasAuthMethods}}null{{/hasAuthMethods}}, {{#returnType}}localVarReturnType{{/returnType}}{{^returnType}}null{{/returnType}}, {{#bodyParam}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/bodyParam}}{{^bodyParam}}false{{/bodyParam}}, localVarErrorTypes);
}
{{#vendorExtensions.x-group-parameters}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class ApiException extends{{#useRuntimeException}} RuntimeException {{/us
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
private Object errorEntity = null;

public ApiException() {}

Expand Down Expand Up @@ -73,6 +74,11 @@ public class ApiException extends{{#useRuntimeException}} RuntimeException {{/us
this.responseBody = responseBody;
}

public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody, Object errorEntity) {
this(code, message, responseHeaders, responseBody);
this.errorEntity = errorEntity;
}

/**
* Get the HTTP status code.
*
Expand All @@ -99,4 +105,13 @@ public class ApiException extends{{#useRuntimeException}} RuntimeException {{/us
public String getResponseBody() {
return responseBody;
}

/**
* Get the deserialized error entity (or null if this error doesn't have a model associated).
*
* @return Deserialized error entity
*/
public Object getErrorEntity() {
return errorEntity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.openapitools.codegen.java.jersey3;

import org.testng.annotations.Test;

import java.util.HashMap;
import java.util.Map;

import static org.testng.Assert.*;

/**
* Functional test for errorEntity deserialization feature.
*
* This test verifies that the generated code includes the errorEntity
* field and getErrorEntity() method by examining the generated templates.
*
* Full integration tests would require:
* 1. A running mock HTTP server
* 2. Generated client code compiled and executed
* 3. Actual API calls to verify runtime behavior
*
* The client's original project (BudgetApiTest) provides this type of
* functional testing. This test verifies the template structure is correct.
*/
public class JavaJersey3ErrorEntityFunctionalTest {

private static final String JERSEY3_TEMPLATE_DIR =
"src/main/resources/Java/libraries/jersey3/";

/**
* Verify generated code includes errorEntity field in ApiException
*/
@Test
public void testGeneratedApiExceptionHasErrorEntity() throws Exception {
String template = readTemplate("apiException.mustache");
assertNotNull(template);

// Verify errorEntity field exists
assertTrue(template.contains("private Object errorEntity = null"),
"Generated ApiException should have errorEntity field");

// Verify getErrorEntity() method exists
assertTrue(template.contains("public Object getErrorEntity()"),
"Generated ApiException should have getErrorEntity() method");

// Verify constructor with errorEntity parameter
assertTrue(template.contains("Object errorEntity"),
"Generated ApiException should accept errorEntity in constructor");
}

/**
* Verify generated code includes deserializeErrorEntity method
*/
@Test
public void testGeneratedApiClientHasDeserializeErrorEntity() throws Exception {
String template = readTemplate("ApiClient.mustache");
assertNotNull(template);

// Verify deserializeErrorEntity method exists
assertTrue(template.contains("deserializeErrorEntity"),
"Generated ApiClient should have deserializeErrorEntity method");

// Verify errorTypes parameter handling
assertTrue(template.contains("Map<String, GenericType> errorTypes"),
"Generated ApiClient should handle errorTypes parameter");
}

/**
* Verify generated API methods build error types map
*/
@Test
public void testGeneratedApiMethodsBuildErrorTypesMap() throws Exception {
String template = readTemplate("api.mustache");
assertNotNull(template);

// Verify localVarErrorTypes is built
assertTrue(template.contains("localVarErrorTypes"),
"Generated API methods should build localVarErrorTypes");

// Verify error types are put into the map
assertTrue(template.contains("localVarErrorTypes.put"),
"Generated API methods should put error types into map");
}

/**
* Verify null is returned when deserialization fails
*/
@Test
public void testDeserializationReturnsNullOnFailure() throws Exception {
String template = readTemplate("ApiClient.mustache");
assertNotNull(template);

// Verify that on exception, null is returned (not error message)
// This is the fix we applied for the P2 issue
assertFalse(template.contains("String.format(\"Failed deserializing"),
"deserializeErrorEntity should return null, not error message string");
}

/**
* Helper method to read template files
*/
private String readTemplate(String templateName) throws Exception {
java.nio.file.Path templatePath = java.nio.file.Paths.get(JERSEY3_TEMPLATE_DIR + templateName);
if (java.nio.file.Files.exists(templatePath)) {
return java.nio.file.Files.readString(templatePath);
}
return null;
}
}
Loading