Refine search
private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request, HttpStatus status, Throwable ex, Level logLevel) { String message = ex.getMessage(); printLog(message, ex, logLevel); Map<String, Object> errorAttributes = new HashMap<>(); boolean errorHandled = false; if (ex instanceof HttpStatusCodeException) { try { //try to extract the original error info if it is thrown from apollo programs, e.g. admin service errorAttributes = gson.fromJson(((HttpStatusCodeException) ex).getResponseBodyAsString(), mapType); status = ((HttpStatusCodeException) ex).getStatusCode(); errorHandled = true; } catch (Throwable th) { //ignore } } if (!errorHandled) { errorAttributes.put("status", status.value()); errorAttributes.put("message", message); errorAttributes.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); errorAttributes.put("exception", ex.getClass().getName()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); return new ResponseEntity<>(errorAttributes, headers, status); }
result = "Get FAILED with HttpStatusCode: " + e.getStatusCode() + "|" + e.getStatusText(); } catch (RuntimeException e) { result = "Get FAILED\n" + ExceptionUtils.getFullStackTrace(e);
/** * Construct instance with an {@link HttpStatus}, status text, content, and * a response charset. * @param statusCode the status code * @param statusText the status text * @param responseHeaders the response headers, may be {@code null} * @param responseBody the response body content, may be {@code null} * @param responseCharset the response body charset, may be {@code null} * @since 3.1.2 */ protected HttpStatusCodeException(HttpStatus statusCode, String statusText, @Nullable HttpHeaders responseHeaders, @Nullable byte[] responseBody, @Nullable Charset responseCharset) { super(getMessage(statusCode, statusText), statusCode.value(), statusText, responseHeaders, responseBody, responseCharset); this.statusCode = statusCode; }
@Test // SPR-16318 public void exceptionFromMethodWithProducesCondition() throws Exception { try { HttpHeaders headers = new HttpHeaders(); headers.add("Accept", "text/csv, application/problem+json"); performGet("/SPR-16318", headers, String.class).getBody(); fail(); } catch (HttpStatusCodeException ex) { assertEquals(500, ex.getRawStatusCode()); assertEquals("application/problem+json;charset=UTF-8", ex.getResponseHeaders().getContentType().toString()); assertEquals("{\"reason\":\"error\"}", ex.getResponseBodyAsString()); } }
@Nullable @Override public VaultResponse read(VaultToken token) { return vaultOperations.doWithVault(restOperations -> { HttpHeaders headers = VaultHttpHeaders.from(token); try { return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, new HttpEntity<>(headers), VaultResponse.class).getBody(); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } if (e.getStatusCode() == HttpStatus.BAD_REQUEST && e.getResponseBodyAsString().contains("does not exist")) { return null; } throw VaultResponses.buildException(e, "sys/wrapping/unwrap"); } }); }
} catch (HttpStatusCodeException httpStatusCodeException) { logger.error("HTTP Error code={} status={}\nresponse={}" , httpStatusCodeException.getStatusCode().value() , httpStatusCodeException.getStatusText() , httpStatusCodeException.getResponseBodyAsString() ); Integer jsonErrorCode = DefaultHttpStatusCodeProvider.INSTANCE.getJsonRpcCode(httpStatusCodeException.getStatusCode().value()); if (jsonErrorCode == null) { jsonErrorCode = httpStatusCodeException.getStatusCode().value(); throw new JsonRpcClientException(jsonErrorCode, httpStatusCodeException.getStatusText(), null); } catch (HttpMessageConversionException httpMessageConversionException) { logger.error("Can not convert (request/response)", httpMessageConversionException);
@ExceptionHandler(HttpStatusCodeException.class) public ResponseEntity<Map<String, Object>> restTemplateException(HttpServletRequest request, HttpStatusCodeException ex) { return handleError(request, ex.getStatusCode(), ex); }
@Override @SuppressWarnings("unchecked") public Map<String, Object> getIndexInfo(String id) throws SearchException { String getUrl = createBaseUrl(URL_GET_INDEX_INFO); try { return restTemplate.getForObject(getUrl, Map.class, id); } catch (HttpStatusCodeException e) { throw getSearchException(id, "Get info for index '" + id + "' failed: [" + e.getStatusText() + "] " + e.getResponseBodyAsString(), e); } catch (Exception e) { throw new SearchException(id, "Get info for index '" + id + "' failed: " + e.getMessage(), e); } }
ResponseEntity<VaultResponse> entity = restOperations.exchange( "auth/{mount}/role/{role}/role-id", HttpMethod.GET, createHttpEntity(token), VaultResponse.class, options.getPath(), throw new VaultLoginException(String.format( "Cannot get Role id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e); ResponseEntity<VaultResponse> entity = restOperations.exchange( "cubbyhole/response", HttpMethod.GET, createHttpEntity(token), VaultResponse.class); VaultResponse response = VaultResponses.unwrap( (String) data.get("response"), VaultResponse.class); throw new VaultLoginException(String.format( "Cannot unwrap Role id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e);
/** * @param headers must not be {@literal null}. * @param backend secret backend mount path, must not be {@literal null}. * @param key key within the key-value secret backend, must not be {@literal null}. * @return */ @Override public String getData(HttpHeaders headers, String backend, String key) { try { String urlTemplate = String.format("%s/v1/%s/%s", baseUrl, backend, getPath()); ResponseEntity<VaultResponse> response = rest.exchange(urlTemplate, HttpMethod.GET, new HttpEntity<>(headers), VaultResponse.class, key); HttpStatus status = response.getStatusCode(); if (status == HttpStatus.OK) { return extractDataFromBody(response.getBody()); } } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } throw e; } return null; } }
); } catch (HttpStatusCodeException e) { log.error("Failed killing job on {}. Error: {}", forwardHost, e.getMessage()); response.sendError(e.getStatusCode().value(), e.getStatusText()); } catch (Exception e) { log.error("Failed killing job on {}. Error: {}", forwardHost, e.getMessage());
private static String format(String message, HttpStatusCodeException e) { return String.format("%s: Status %s %s %s", message, e.getRawStatusCode(), e.getStatusText(), VaultResponses.getError(e.getResponseBodyAsString())); }
@ExceptionHandler @ResponseBody public ResponseEntity<Object> handleStatusCodeException(HttpStatusCodeException e) { // Map the status to a 500 unlesss it's a 401. If that's the case // then we know the client has passed in an invalid X-xxx-Authorization header and it's a 400. logger.error("Backend returned {} {} \n {}", e.getStatusCode(), e.getStatusCode().getReasonPhrase(), e.getResponseBodyAsString()); String backendStatus = Integer.toString(e.getRawStatusCode()); if (e.getStatusCode() == UNAUTHORIZED) { Map<String, String> body = Collections.singletonMap("error", "invalid_connector_token"); return ResponseEntity.status(BAD_REQUEST) .header(BACKEND_STATUS, backendStatus) .contentType(APPLICATION_JSON) .body(body); } else { BodyBuilder builder = ResponseEntity.status(INTERNAL_SERVER_ERROR) .header(BACKEND_STATUS, backendStatus); if (e.getResponseHeaders().getContentType() != null) { builder.contentType(e.getResponseHeaders().getContentType()); } return builder.body(e.getResponseBodyAsString()); } } }
private void processStatusCodeException(HttpStatusCodeException e, ServiceCallResult res, URI uri) { setCode(e.getStatusCode(), res); String msg = null; try { if(MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) { objectMapper.reader().withValueToUpdate(res).readValue(e.getResponseBodyAsString()); msg = res.getMessage(); } } catch (Exception ex) { log.error("Can not process status code exception message.", ex); } // in some cases msg may be null on success reading value, but anyway we need to make non null value manually if(msg == null) { msg = formatHttpException(e); res.setMessage(msg); } // we log message as debug because consumer code must log error too, but with high level, // when we log it as warn then error will cause to many duplicate lines in log log.warn("Fail to execute '{}' due to error: {}", uri, msg); }
public static String toString(HttpStatusCodeException e) { Map<String, Object> errorAttributes = gson.fromJson(e.getResponseBodyAsString(), mapType); if (errorAttributes != null) { return MoreObjects.toStringHelper(HttpStatusCodeException.class).omitNullValues() .add("status", errorAttributes.get("status")) .add("message", errorAttributes.get("message")) .add("timestamp", errorAttributes.get("timestamp")) .add("exception", errorAttributes.get("exception")) .add("errorCode", errorAttributes.get("errorCode")) .add("stackTrace", errorAttributes.get("stackTrace")).toString(); } return ""; } }
private static Map<String, Object> lookupSelf(RestOperations restOperations, VaultToken token) { try { ResponseEntity<VaultResponse> entity = restOperations.exchange( "auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>( VaultHttpHeaders.from(token)), VaultResponse.class); Assert.state(entity.getBody() != null && entity.getBody().getData() != null, "Token response is null"); return entity.getBody().getData(); } catch (HttpStatusCodeException e) { throw new VaultTokenLookupException(String.format( "Token self-lookup failed: %s %s", e.getRawStatusCode(), VaultResponses.getError(e.getResponseBodyAsString()))); } catch (RestClientException e) { throw new VaultTokenLookupException("Token self-lookup failed", e); } }
if (httpException.getStatusCode() == HttpStatus.BAD_REQUEST) { onLeaseExpired(requestedSecret, lease); new VaultException(String.format("Cannot renew lease: %s", VaultResponses.getError(httpException .getResponseBodyAsString()))));
@Override public void run() { while (running.get()) { try { readStream(twitter.getRestTemplate()); } catch (HttpStatusCodeException sce) { if (sce.getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.error("Twitter authentication failed: " + sce.getMessage(), sce); running.set(false); } else if (420 == sce.getStatusCode().value()) { waitRateLimitBackoff(); } else { waitHttpErrorBackoff(sce); } } catch (Exception e) { logger.warn("Exception while reading stream.", e); waitLinearBackoff(); } } }
@Override public VaultHealth doWithRestOperations(RestOperations restOperations) { try { ResponseEntity<VaultHealthImpl> healthResponse = restOperations.exchange( "sys/health", HttpMethod.GET, null, VaultHealthImpl.class); return healthResponse.getBody(); } catch (HttpStatusCodeException responseError) { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(responseError.getResponseBodyAsString(), VaultHealthImpl.class); } catch (Exception jsonError) { throw responseError; } } } }
@Nullable private <T> T doRead(String path, Class<T> responseType) { return doWithSession(restOperations -> { try { return restOperations.getForObject(path, responseType); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } throw VaultResponses.buildException(e, path); } }); } }