Skip to content

Commit d977d7e

Browse files
committed
SOLR-17549: v2 SolrRequest/SolrResponse should throw exception on error (#4183)
This commit updates our v2 SolrJ code to throw RemoteSolrException when error-responses are encountered. It relies on a pre-existing attempt at error detection already present in our SolrClient implementations. Code in many of our clients already attempts to detect these errors by looking for a 'NamedList' key, "error", which it (incorrectly) assumed would be present in the v2 case but which isn't populated by the ResponseParser that our v2 SolrRequest/SolrResponse implementations use by default. This commit updates JacksonDatabindResponseParser to populate this "error" key that SolrClient's were looking for, which in turn enables the clients to correctly throw RemoteSolrException in these cases.
1 parent c537e42 commit d977d7e

File tree

6 files changed

+215
-22
lines changed

6 files changed

+215
-22
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
title: SOLR-17549 - v2 SolrRequest/SolrResponse classes now report errors identically to their v1 counterparts
2+
type: fixed
3+
authors:
4+
- name: Jason Gerlowski
5+
links:
6+
- name: SOLR-17549
7+
url: https://issues.apache.org/jira/browse/SOLR-17549

solr/core/src/test/org/apache/solr/filestore/TestDistribFileStore.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,16 @@ public void testFileStoreManagement() throws Exception {
175175
final var fetchReq = new FileStoreApi.FetchFile("/package/mypkg/v1.0/runtimelibs.jar2");
176176
fetchReq.setGetFrom("someFakeSolrNode:8983_solr");
177177
try (final var solrClient = jettySolrRunner.newClient()) {
178-
final var asdf = fetchReq.process(solrClient);
179-
assertEquals(400, asdf.responseHeader.status);
180-
assertThat(asdf.error.msg, containsString("File store cannot fetch from source node"));
181-
assertThat(asdf.error.msg, containsString("does not appear in live-nodes"));
178+
final var expectedExc =
179+
expectThrows(
180+
RemoteSolrException.class,
181+
() -> {
182+
fetchReq.process(solrClient);
183+
});
184+
assertEquals(400, expectedExc.code());
185+
assertThat(
186+
expectedExc.getMessage(), containsString("File store cannot fetch from source node"));
187+
assertThat(expectedExc.getMessage(), containsString("does not appear in live-nodes"));
182188
}
183189
}
184190

solr/core/src/test/org/apache/solr/handler/V2ApiIntegrationTest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
package org.apache.solr.handler;
1919

20+
import static org.hamcrest.Matchers.containsString;
21+
2022
import java.io.IOException;
2123
import java.nio.file.Path;
2224
import java.util.HashMap;
@@ -31,7 +33,10 @@
3133
import org.apache.solr.client.solrj.SolrServerException;
3234
import org.apache.solr.client.solrj.apache.CloudLegacySolrClient;
3335
import org.apache.solr.client.solrj.impl.CloudSolrClient;
36+
import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
3437
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
38+
import org.apache.solr.client.solrj.request.CollectionsApi;
39+
import org.apache.solr.client.solrj.request.GenericV2SolrRequest;
3540
import org.apache.solr.client.solrj.request.V2Request;
3641
import org.apache.solr.client.solrj.response.InputStreamResponseParser;
3742
import org.apache.solr.client.solrj.response.JavaBinResponseParser;
@@ -257,6 +262,43 @@ public void testSelect() throws Exception {
257262
assertEquals(0, ((SolrDocumentList) v2Response.getResponse().get("response")).getNumFound());
258263
}
259264

265+
@Test
266+
public void testV2ApiErrorHandling() throws Exception {
267+
final var deleteRequest = new CollectionsApi.DeleteCollection("collection-does-not-exist");
268+
269+
// Test with "Http" client
270+
final String baseUrl = cluster.getJettySolrRunner(0).getBaseUrl().toString();
271+
try (var httpClient = new HttpJettySolrClient.Builder(baseUrl).build()) {
272+
final var ex =
273+
expectThrows(RemoteSolrException.class, () -> deleteRequest.process(httpClient));
274+
assertRSECodeAndMessage(ex, 400, "Could not find collection", "collection-does-not-exist");
275+
}
276+
277+
// Test with "Cloud" client
278+
final var ex =
279+
expectThrows(
280+
RemoteSolrException.class, () -> deleteRequest.process(cluster.getSolrClient()));
281+
assertRSECodeAndMessage(ex, 400, "Could not find collection", "collection-does-not-exist");
282+
283+
// Test with the less desirable Generic option to make sure exception is equivalent.
284+
final var genericDeleteRequest =
285+
new GenericV2SolrRequest(SolrRequest.METHOD.DELETE, "/collections/coll-does-not-exist");
286+
final var ex2 =
287+
expectThrows(
288+
RemoteSolrException.class, () -> genericDeleteRequest.process(cluster.getSolrClient()));
289+
assertRSECodeAndMessage(ex2, 400, "Could not find collection", "coll-does-not-exist");
290+
}
291+
292+
private void assertRSECodeAndMessage(
293+
RemoteSolrException rse, int expectedCode, String... expectedMessagePieces) {
294+
assertEquals(expectedCode, rse.code());
295+
if (expectedMessagePieces != null) {
296+
for (String expectedMessageSubStr : expectedMessagePieces) {
297+
assertThat(rse.getMessage(), containsString(expectedMessageSubStr));
298+
}
299+
}
300+
}
301+
260302
private Map<?, ?> resAsMap(CloudSolrClient client, V2Request request)
261303
throws SolrServerException, IOException {
262304
NamedList<Object> rsp = client.request(request);

solr/core/src/test/org/apache/solr/handler/admin/api/RenameCoreAPITest.java

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.apache.solr.handler.admin.api;
1818

1919
import static org.apache.solr.core.CoreContainer.ALLOW_PATHS_SYSPROP;
20+
import static org.hamcrest.Matchers.containsString;
2021

2122
import java.nio.charset.StandardCharsets;
2223
import org.apache.solr.SolrTestCaseJ4;
@@ -25,7 +26,6 @@
2526
import org.apache.solr.client.solrj.SolrRequest;
2627
import org.apache.solr.client.solrj.request.CoresApi;
2728
import org.apache.solr.client.solrj.request.GenericV2SolrRequest;
28-
import org.apache.solr.common.SolrException;
2929
import org.apache.solr.common.util.EnvUtils;
3030
import org.apache.solr.util.ExternalPaths;
3131
import org.apache.solr.util.SolrJettyTestRule;
@@ -34,19 +34,13 @@
3434
import org.junit.Test;
3535

3636
/**
37-
* The success case and the missing-parameter error case use the generated {@link
38-
* org.apache.solr.client.solrj.request.CoresApi.RenameCore} request type, asserting directly on
39-
* {@link SolrJerseyResponse#responseHeader} status and {@link
40-
* org.apache.solr.client.api.model.ErrorInfo#msg} because the generated typed client uses {@code
41-
* JacksonDataBindResponseParser}, which does not yet propagate errors as exceptions (SOLR-17549).
37+
* Test cases for the v2 {@link RenameCore}
4238
*
4339
* <p>The missing-body error case uses {@link GenericV2SolrRequest} with an explicit {@code "null"}
4440
* JSON body, because {@link org.apache.solr.client.solrj.request.CoresApi.RenameCore} always
4541
* serializes a request body and therefore cannot represent a truly absent body. The standard
4642
* response parser used by {@link GenericV2SolrRequest} does propagate 4xx responses as {@link
4743
* RemoteSolrException}s.
48-
*
49-
* <p>TODO: Deal with this when generated code does properly throw an exception!
5044
*/
5145
public class RenameCoreAPITest extends SolrTestCaseJ4 {
5246

@@ -90,14 +84,14 @@ public void testMissingRequestBodyThrowsError() {
9084

9185
@Test
9286
public void testMissingToParameterThrowsError() throws Exception {
93-
// CoresApi.RenameCore always serializes a body, so leaving setTo() uncalled sends a body
94-
// whose "to" field is null. The handler's ensureRequiredParameterProvided guard returns a 400,
95-
// which JacksonDataBindResponseParser surfaces via the response fields rather than as an
96-
// exception (SOLR-17549), so we assert directly on responseHeader.status and error.msg.
9787
CoresApi.RenameCore renameRequest = new CoresApi.RenameCore(DEFAULT_TEST_CORENAME);
98-
SolrJerseyResponse response = renameRequest.process(solrTestRule.getAdminClient());
99-
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, response.responseHeader.status);
100-
assertNotNull(response.error);
101-
assertTrue(response.error.msg.contains("Missing required parameter: to"));
88+
final var ex =
89+
expectThrows(
90+
RemoteSolrException.class,
91+
() -> {
92+
renameRequest.process(solrTestRule.getAdminClient());
93+
});
94+
assertEquals(400, ex.code());
95+
assertThat(ex.getMessage(), containsString("Missing required parameter: to"));
10296
}
10397
}

solr/solrj/src/java/org/apache/solr/client/solrj/response/json/JacksonDataBindResponseParser.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
import java.io.InputStreamReader;
2323
import java.util.Collection;
2424
import java.util.List;
25+
import java.util.Map;
26+
import org.apache.solr.client.api.model.SolrJerseyResponse;
2527
import org.apache.solr.client.solrj.request.json.JacksonContentWriter;
2628
import org.apache.solr.client.solrj.response.ResponseParser;
2729
import org.apache.solr.common.util.NamedList;
@@ -55,7 +57,6 @@ public Collection<String> getContentTypes() {
5557

5658
@Override
5759
public NamedList<Object> processResponse(InputStream stream, String encoding) throws IOException {
58-
// TODO SOLR-17549 for error handling, implying a significant ResponseParser API change
5960
// TODO generalize to CBOR, Smile, ...
6061
var mapper = JacksonContentWriter.DEFAULT_MAPPER;
6162

@@ -66,6 +67,16 @@ public NamedList<Object> processResponse(InputStream stream, String encoding) th
6667
parsedVal = mapper.readValue(new InputStreamReader(stream, encoding), typeParam);
6768
}
6869

69-
return SimpleOrderedMap.of("response", parsedVal);
70+
final var result = new SimpleOrderedMap<Object>();
71+
result.add("response", parsedVal);
72+
73+
// Surface errors from V2 response POJOs to the top-level NamedList so that
74+
// HttpSolrClientBase.processErrorsAndResponse() can detect and throw RemoteSolrException,
75+
// matching the exception-throwing behavior of V1 API requests.
76+
if (parsedVal instanceof SolrJerseyResponse jerseyResponse && jerseyResponse.error != null) {
77+
result.add("error", mapper.convertValue(jerseyResponse.error, Map.class));
78+
}
79+
80+
return result;
7081
}
7182
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.solr.client.solrj.response.json;
18+
19+
import static org.hamcrest.Matchers.instanceOf;
20+
21+
import java.io.ByteArrayInputStream;
22+
import java.io.IOException;
23+
import java.nio.charset.StandardCharsets;
24+
import java.util.Map;
25+
import org.apache.solr.SolrTestCase;
26+
import org.apache.solr.client.api.model.SolrJerseyResponse;
27+
import org.apache.solr.common.util.NamedList;
28+
import org.junit.Test;
29+
30+
/** Unit tests for {@link JacksonDataBindResponseParser} */
31+
public class JacksonDataBindResponseParserTest extends SolrTestCase {
32+
33+
@Test
34+
public void testSuccessfulResponseHasNoErrorKey() throws IOException {
35+
final var parser = new JacksonDataBindResponseParser<>(SolrJerseyResponse.class);
36+
final var json = "{\"responseHeader\":{\"status\":0,\"QTime\":5}}";
37+
38+
final NamedList<Object> result = parser.processResponse(toStream(json), null);
39+
40+
assertNotNull(result.get("response"));
41+
assertThat(result.get("response"), instanceOf(SolrJerseyResponse.class));
42+
assertNull("No 'error' key expected on success", result.get("error"));
43+
}
44+
45+
@Test
46+
public void testErrorResponseSurfacesErrorAtTopLevel() throws IOException {
47+
final var parser = new JacksonDataBindResponseParser<>(SolrJerseyResponse.class);
48+
final var json =
49+
"{"
50+
+ "\"responseHeader\":{\"status\":400,\"QTime\":3},"
51+
+ "\"error\":{"
52+
+ " \"code\":400,"
53+
+ " \"errorClass\":\"org.apache.solr.common.SolrException\","
54+
+ " \"msg\":\"Bad collection name\""
55+
+ "}"
56+
+ "}";
57+
58+
final NamedList<Object> result = parser.processResponse(toStream(json), null);
59+
60+
// The deserialized POJO is present under "response"
61+
assertNotNull(result.get("response"));
62+
assertThat(result.get("response"), instanceOf(SolrJerseyResponse.class));
63+
final var responsePojo = (SolrJerseyResponse) result.get("response");
64+
65+
// Error is present in the deserialized POJO
66+
assertNotNull("Error should be populated in the POJO", responsePojo.error);
67+
68+
// Error is also present on NL for clients to detect
69+
assertNotNull(result.get("error"));
70+
assertThat(result.get("error"), instanceOf(Map.class));
71+
@SuppressWarnings("unchecked")
72+
final var topLevelError = (Map<String, Object>) result.get("error");
73+
assertEquals(400, topLevelError.get("code"));
74+
assertEquals("org.apache.solr.common.SolrException", topLevelError.get("errorClass"));
75+
assertEquals("Bad collection name", topLevelError.get("msg"));
76+
}
77+
78+
@Test
79+
public void testErrorResponseIncludesMetadataAtTopLevel() throws IOException {
80+
final var parser = new JacksonDataBindResponseParser<>(SolrJerseyResponse.class);
81+
final var json =
82+
"""
83+
{
84+
"responseHeader":{
85+
"status":500,
86+
"QTime":1
87+
},
88+
"error": {
89+
"code":500,
90+
"errorClass": "org.apache.solr.common.SolrException",
91+
"msg": "Internal error",
92+
"metadata":{
93+
"error-class": "org.apache.solr.common.SolrException",
94+
"root-error-class": "java.lang.IllegalStateException"
95+
}
96+
}
97+
}""";
98+
99+
final NamedList<Object> result = parser.processResponse(toStream(json), null);
100+
101+
@SuppressWarnings("unchecked")
102+
final var topLevelError = (Map<String, Object>) result.get("error");
103+
assertNotNull(topLevelError);
104+
105+
@SuppressWarnings("unchecked")
106+
final var metadata = (Map<String, Object>) topLevelError.get("metadata");
107+
assertNotNull("Metadata must be present for RemoteSolrException to extract it", metadata);
108+
assertEquals("org.apache.solr.common.SolrException", metadata.get("error-class"));
109+
assertEquals("java.lang.IllegalStateException", metadata.get("root-error-class"));
110+
}
111+
112+
@Test
113+
public void testNonJerseyResponseTypeIsUnaffected() throws IOException {
114+
// A parser bound to a plain POJO (i.e. not SolrJerseyResponse) must not add an "error" key
115+
final var parser = new JacksonDataBindResponseParser<>(PlainPojo.class);
116+
final var json = "{\"value\":\"hello\"}";
117+
118+
final NamedList<Object> result = parser.processResponse(toStream(json), null);
119+
120+
assertNotNull(result.get("response"));
121+
assertThat(result.get("response"), instanceOf(PlainPojo.class));
122+
assertNull("Error extraction only occurs for SolrJerseyResponse types", result.get("error"));
123+
}
124+
125+
// Minimal POJO for the non-SolrJerseyResponse test above
126+
public static class PlainPojo {
127+
public String value;
128+
}
129+
130+
private static ByteArrayInputStream toStream(String json) {
131+
return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
132+
}
133+
}

0 commit comments

Comments
 (0)