if (rawObject instanceof JsonObject) { JsonObject object = (JsonObject) rawObject; Category category = getCategory(object); String message = getMessage(object); RpcCallException retval = new RpcCallException(category, message); JsonElement element = object.get(SOURCE); if (element != null && !(element instanceof JsonNull)) { retval.withSource(element.getAsString()); retval.withErrorCode(element.getAsString()); retval.withData(element.getAsString()); retval.withRetriable(element.getAsBoolean());
@Test public void testJsonEncodingDecoding() throws Exception { RpcCallException exception = new RpcCallException(RpcCallException.Category.BadRequest, "You fool!").withData("my data").withErrorCode("SERVICE_PROTOBUF_ENUM"). withRetriable(true).withSource("com.sixt.service.foobar"); String json = exception.toString(); assertThat(json).isEqualTo("{\"category\":400,\"message\":\"You fool!\"," + "\"source\":\"com.sixt.service.foobar\",\"code\":\"SERVICE_PROTOBUF_ENUM\"," + "\"data\":\"my data\",\"retriable\":true}"); RpcCallException.fromJson(json); }
@Test public void testFromJson_mediumBadData() { String error = "{\"sxerror\":\"1\",\"source\":\"go.micro.client\",\"category\":408,\"code\":\"unexpected_error\",\"message\":\"call timeout: context deadline exceeded\",\"data\":\"'*errors.Error' with error '{\\\"id\\\":\\\"go.micro.client\\\",\\\"code\\\":408,\\\"detail\\\":\\\"call timeout: context deadline exceeded\\\",\\\"status\\\":\\\"Request Timeout\\\"}' cannot be mapped to a known representation. Data: \\u0026errors.Error{Id:\\\"go.micro.client\\\", Code:408, Detail:\\\"call timeout: context deadline exceeded\\\", Status:\\\"Request Timeout\\\"}\",\"retriable\":false}"; RpcCallException ex = RpcCallException.fromJson(error); assertThat(ex).isNotNull(); assertThat(ex.getCategory()).isEqualTo(RpcCallException.Category.InternalServerError); // Switch to default Category when assertThat(ex.getErrorCode()).isEqualTo("unexpected_error"); assertThat(ex.getMessage()).isEqualTo("call timeout: context deadline exceeded"); assertThat(ex.getData()).isNotNull(); assertThat(ex.isRetriable()).isFalse(); }
@Override public RpcCallException decodeException(ContentResponse response) throws RpcCallException { try { if (response != null) { JsonObject json = (JsonObject) new JsonParser().parse(response.getContentAsString()); JsonElement error = json.get("error"); if (error != null) { return RpcCallException.fromJson(error.toString()); } } } catch (Exception ex) { logger.warn("Caught exception decoding protobuf response exception", ex); throw new RpcCallException(RpcCallException.Category.InternalServerError, RpcCallExceptionDecoder.exceptionToString(ex)); } return null; }
@Test public void retriableError() { //Create 2 servers and have both throw an exception that is retriable. //The exception should be thrown locally loadBalancer.addServiceEndpoint(new ServiceEndpoint(executor, "localhost:20001", "dc1", dependencyHealthCheck)); loadBalancer.addServiceEndpoint(new ServiceEndpoint(executor, "localhost:20002", "dc1", dependencyHealthCheck)); rpcClient = clientFactory.newClient(serviceName, "testing", FrameworkTest.Foobar.class). withRetries(1).build(); httpClient.setResponseException(new RpcCallException(RpcCallException.Category. InternalServerError, "test1234").withSource("testing567")); int failureCount = 0; try { rpcClient.callSynchronous(FrameworkTest.Foobar.newBuilder().build(), new OrangeContext()); } catch (RpcCallException ex) { failureCount++; assertThat(ex.getCategory()).isEqualTo(RpcCallException.Category.InternalServerError); assertThat(ex.getMessage()).isEqualTo("test1234"); assertThat(ex.getSource()).isEqualTo("testing567"); } assertThat(failureCount).isEqualTo(1); assertThat(httpClient.verifyRequestsProcessed(2)).isTrue(); }
public static JsonRpcResponse fromString(String rawResponse) { JsonParser parser = new JsonParser(); JsonObject response = parser.parse(rawResponse).getAsJsonObject(); JsonElement id = response.get("id"); JsonElement errorElement = response.get("error"); int responseStatus = HttpServletResponse.SC_OK; String error; if (! (errorElement instanceof JsonNull)) { if (errorElement instanceof JsonObject) { error = errorElement.toString(); // try parsing it into RpcCallException to get the HttpStatus from there RpcCallException rpcEx = RpcCallException.fromJson(error); if (rpcEx != null) { responseStatus = rpcEx.getCategory().getHttpStatus(); JsonElement resultElement = response.get("result"); return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement, errorElement, responseStatus); } } error = errorElement.getAsString(); if (StringUtils.isNotBlank(error)) { responseStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } JsonElement resultElement = response.get("result"); return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement, errorElement, responseStatus); }
@Test public void testFromJson_ErrorWithDetailInsteadOfMessage() { String error = "{\"id\":\"com.sixt.service.foobar\",\"code\":500,\"detail\":\"error message\",\"status\":\"Internal Server Error\"}"; RpcCallException ex = RpcCallException.fromJson(error); assertThat(ex.getCategory()).isEqualTo(RpcCallException.Category.InternalServerError); assertThat(ex.getMessage()).isEqualTo("error message"); }
} catch (TimeoutException timeout) { lastStatusCode = RpcCallException.Category.RequestTimedOut.getHttpStatus(); lastException = new RpcCallException(RpcCallException.Category.RequestTimedOut, "Http-client timeout"); if (lastException != null && !lastException.isRetriable()) { throw lastException; throw new RpcCallException(RpcCallException.Category.fromStatus(lastStatusCode), "Null response in execute").withSource(serviceProps.getServiceName()); } else { throw lastException;
@Test public void decodeException_nullContentPassed_InternalServerErrorShouldBeReturned() throws RpcCallException { byte[] content = null; RpcCallException exception = decoder.decodeException(response(content)); assertThat(exception.getCategory()).isEqualTo(InternalServerError); assertThat(exception.getMessage()).isEqualTo("Empty response received"); }
public HttpRequestWrapper createHttpPost(RpcClient client) throws RpcCallException { this.client = client; ServiceEndpoint instance = loadBalancer.getHealthyInstance(); if (instance == null) { throw new RpcCallException(RpcCallException.Category.InternalServerError, "No available instance of " + loadBalancer.getServiceName()). withSource(serviceProps.getServiceName()); } return new HttpRequestWrapper("POST", instance); }
@SuppressWarnings("unchecked") private JsonRpcResponse dispatchJsonRpcRequest(JsonRpcRequest rpcRequest, OrangeContext cxt) { JsonRpcResponse jsonResponse = new JsonRpcResponse(rpcRequest.getId(), JsonNull.INSTANCE, JsonNull.INSTANCE, HttpServletResponse.SC_OK); try { ServiceMethodHandler handler = handlers.getMethodHandler(rpcRequest.getMethod()); Message innerRequest = convertJsonToProtobuf(handler, rpcRequest); JsonElement idElement = rpcRequest.getId(); if (idElement == null) { jsonResponse.setId(new JsonPrimitive(-1)); } Message innerResponse = invokeHandlerChain(rpcRequest.getMethod(), handler, innerRequest, cxt); jsonResponse.setResult(ProtobufUtil.protobufToJson(innerResponse)); } catch (RpcCallException rpcEx) { logger.debug("Error processing request", rpcEx); jsonResponse.setError(rpcEx.toJson()); jsonResponse.setStatusCode(rpcEx.getCategory().getHttpStatus()); } catch (Exception ex) { logger.warn("Error processing request", ex); if (ex.getMessage() != null) { jsonResponse.setError(new JsonPrimitive(ex.getMessage())); } jsonResponse.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return jsonResponse; }
private void initialize() { httpResponse = mock(ContentResponse.class); when(httpResponse.getHeaders()).thenReturn(new HttpFields()); when(httpResponse.getStatus()).thenReturn(200); try { RpcEnvelope.Response.Builder responseBuilder = RpcEnvelope.Response.newBuilder(); responseBuilder.setServiceMethod("Test.test"); if (requestsFail) { RpcCallException callException = new RpcCallException( RpcCallException.Category.InternalServerError, "requests fail!"); responseBuilder.setError(callException.toJson().toString()); } RpcEnvelope.Response rpcResponse = responseBuilder.build(); byte[] responseHeader = rpcResponse.toByteArray(); byte[] payload = FrameworkTest.Foobar.newBuilder().build().toByteArray(); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(Ints.toByteArray(responseHeader.length)); out.write(responseHeader); out.write(Ints.toByteArray(payload.length)); out.write(payload); out.flush(); when(httpResponse.getContent()).thenReturn(out.toByteArray()); } catch (Exception e) { e.printStackTrace(); } }
@Test public void testJsonToString() { RpcCallException ex = new RpcCallException(RpcCallException.Category.InternalServerError, "feckoff"); System.out.println(ex.toString()); }
private byte[] readyFully(ServletInputStream in, int totalSize) throws Exception { byte[] retval = new byte[totalSize]; int bytesRead = 0; while (bytesRead < totalSize) { try { int read = in.read(retval, bytesRead, totalSize - bytesRead); if (read == -1) { throw new RpcCallException(RpcCallException.Category.InternalServerError, "Unable to read complete request or response"); } bytesRead += read; } catch (IOException e) { throw new RpcCallException(RpcCallException.Category.InternalServerError, "IOException reading data: " + e); } } return retval; }
context.getRpcOriginMethod()); } catch (RpcCallException rpcEx) { sendErrorResponse(resp, rpcRequest, rpcEx.toString(), rpcEx.getCategory().getHttpStatus()); if (span != null) { Tags.ERROR.set(span, true);
@Test public void noInstances() { //no service endpoints available int errorCount = 0; try { rpcClient.callSynchronous(FrameworkTest.Foobar.newBuilder().build(), new OrangeContext()); } catch (RpcCallException ex) { errorCount++; assertThat(ex.getCategory()).isEqualTo(RpcCallException.Category.InternalServerError); } assertThat(errorCount).isEqualTo(1); }
@Override public String toString() { return toJson().toString(); }
@Test public void testFromInvalidJson() { String error = "invalid json"; RpcCallException ex = RpcCallException.fromJson(error); assertThat(ex).isNull(); }
} catch (RpcCallException ex) { if (giveWarning) { logger.info("Getting configuration failed, will retry. {}", ex.toString()); giveWarning = false;
when(exception.isRetriable()).thenReturn(true); when(decoder.decodeException(any(ContentResponse.class))).thenReturn(exception); when(rpcClient.getRetryBackOffFunction())