/** * Handle Error Events * * @param response * @param error */ @Override protected void interceptResponse(CocWebApiResponse response, Throwable error) { if (error != null) throw new CocWebApiException(error); if (response.getStatus() == HttpStatusClass.CLIENT_ERROR) { if (response.getProcessedContent() != null) { CocErrorResponse err = builder().fromJson(response.getProcessedContent(), CocErrorResponse.class); log.error("[ERROR FROM {}]: Reason: {}, Message: {}", response.sender(), err.getReason(), err.getMessage()); } switch (response.getMessage().getStatusCode()) { case 400: throw new CocIncorrectParametersException("Incorrect parameters provided for request"); default: break; } //Let the base class handle the rest super.interceptResponse(response, error); } }
/** * The default error handler. Override this if needed. * * @param response An instance of {@link AbstractWebApiResponse} or <code>null</code> if an exception was thrown. * @param error A {@link Throwable} instance or <code>null</code> if no error has occured. * * @throws WebException thrown if a server/client error occurs */ protected void interceptResponse(Res response, Throwable error) { if (error != null) throw new WebException(error); log.debug("Handling response for {}, with status code = {}", response.getMessage().getUri(), response.getMessage().getStatusCode()); if (response.getStatus() == HttpStatusClass.SERVER_ERROR || response.getStatus() == HttpStatusClass.CLIENT_ERROR) { switch (response.getMessage().getStatusCode()) { case 400: throw new BadRequestException("Incorrect parameters provided for request"); case 403: throw new AccessDeniedException("Access denied, either because of missing/incorrect credentials or used API token does not grant access to the requested resource."); case 404: throw new ResourceNotFoundException("Resource was not found."); case 429: throw new TooManyRequestsException("Request was throttled, because amount of requests was above the threshold defined for the used API token."); case 500: throw new UnknownWebException("An internal error occured in server"); case 503: throw new ServiceUnavailableException("Service is temprorarily unavailable. Possible maintenance on-going."); default: throw new WebException("Unknown error occured on request send"); } } }
public static TransportErrorResponse toTransportErrorResponse( HttpResponseStatus status, TransportBody body) { Single<TransportException> exception = body.accumulate() .map( bytes -> { String message = new String(bytes, Charsets.UTF_8).trim(); if (HttpResponseStatus.GATEWAY_TIMEOUT.equals(status)) { return new RemoteTimeoutException(message); } else if (HttpStatusClass.CLIENT_ERROR.equals(status.codeClass())) { return new RemoteBadRequestException(message); } else { return new RemoteUnexpectedException(message); } }); return new DefaultTransportErrorResponse(exception); }
private static void performAuthenticationCheck() { long timeStamp = System.currentTimeMillis(); get(BUILDS_SINCE_RESOURCE + timeStamp) .doOnNext(response -> { //expected response is 204 due no builds being there LOGGER.info("Received a status code of {} from: " + BUILDS_SINCE_RESOURCE + timeStamp, response.getStatus()); if (!response.getStatus().codeClass().equals(HttpStatusClass.SUCCESS)) { throw new RuntimeException("AuthenticationCheck failed. Status: " + response.getStatus()); } }).flatMap(response -> response.getContent() .map(bb -> bb.toString(Charset.defaultCharset()))) .toBlocking() .forEach(LOGGER::info); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse && ((HttpResponse) msg).status().codeClass() != HttpStatusClass.INFORMATIONAL) { sentResponses++; } ctx.write(msg, promise); }
@Test public void testRequestTimeoutInvocation() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { final HttpPost req = new HttpPost(server.uri("/timeout")); req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8)); try (CloseableHttpResponse res = hc.execute(req)) { assertThat(HttpStatusClass.valueOf(res.getStatusLine().getStatusCode())) .isNotEqualTo(HttpStatusClass.SUCCESS); } } }
@Test public void testDynamicRequestTimeoutInvocation() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { final HttpPost req = new HttpPost(server.uri("/timeout-not")); req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8)); try (CloseableHttpResponse res = hc.execute(req)) { assertThat(HttpStatusClass.valueOf(res.getStatusLine().getStatusCode())) .isEqualTo(HttpStatusClass.SUCCESS); } } }
protected boolean handleResponseStatus( final O ioTask, final HttpStatusClass statusClass, final HttpResponseStatus responseStatus ) { switch(statusClass) { case INFORMATIONAL: Loggers.ERR.warn("{}: {}", ioTask.toString(), responseStatus.toString()); ioTask.setStatus(RESP_FAIL_CLIENT); break; case SUCCESS: ioTask.setStatus(SUCC); return true; case REDIRECTION: Loggers.ERR.warn("{}: {}", ioTask.toString(), responseStatus.toString()); ioTask.setStatus(RESP_FAIL_CLIENT); break; case CLIENT_ERROR: Loggers.ERR.warn("{}: {}", ioTask.toString(), responseStatus.toString()); if(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE.equals(responseStatus)) { ioTask.setStatus(RESP_FAIL_SVC); } else if(HttpResponseStatus.REQUEST_URI_TOO_LONG.equals(responseStatus)) { ioTask.setStatus(RESP_FAIL_SVC); } else if(HttpResponseStatus.UNAUTHORIZED.equals(responseStatus)) { ioTask.setStatus(RESP_FAIL_AUTH); } else if(HttpResponseStatus.FORBIDDEN.equals(responseStatus)) { ioTask.setStatus(RESP_FAIL_AUTH); } else if(HttpResponseStatus.NOT_FOUND.equals(responseStatus)) { ioTask.setStatus(RESP_FAIL_NOT_FOUND); } else { ioTask.setStatus(RESP_FAIL_CLIENT); } break; case SERVER_ERROR: Loggers.ERR.warn("{}: {}", ioTask.toString(), responseStatus.toString()); if(HttpResponseStatus.GATEWAY_TIMEOUT.equals(responseStatus)) { ioTask.setStatus(FAIL_TIMEOUT); } else if(HttpResponseStatus.INSUFFICIENT_STORAGE.equals(responseStatus)) { ioTask.setStatus(RESP_FAIL_SPACE); } else { ioTask.setStatus(RESP_FAIL_SVC); } break; case UNKNOWN: Loggers.ERR.warn("{}: {}", ioTask.toString(), responseStatus.toString()); ioTask.setStatus(FAIL_UNKNOWN); break; } return false; }
public HttpStatusClass getStatus() { return HttpStatusClass.valueOf(this.response.getStatusCode()); }
static boolean isInformational(HttpResponse response) { return response.status() .codeClass() == HttpStatusClass.INFORMATIONAL; }
/** * Provided a cause, returns an error response with the right status and error message. * @param cause the cause of the error. * @return a {@link FullHttpResponse} with the error message that can be sent to the client. */ private FullHttpResponse getErrorResponse(Throwable cause) { HttpResponseStatus status; RestServiceErrorCode restServiceErrorCode = null; String errReason = null; if (cause instanceof RestServiceException) { restServiceErrorCode = ((RestServiceException) cause).getErrorCode(); errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode); status = getHttpResponseStatus(errorResponseStatus); if (status == HttpResponseStatus.BAD_REQUEST) { errReason = new String( Utils.getRootCause(cause).getMessage().replaceAll("[\n\t\r]", " ").getBytes(StandardCharsets.US_ASCII), StandardCharsets.US_ASCII); } } else if (Utils.isPossibleClientTermination(cause)) { nettyMetrics.clientEarlyTerminationCount.inc(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; errorResponseStatus = ResponseStatus.InternalServerError; } else { nettyMetrics.internalServerErrorCount.inc(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; errorResponseStatus = ResponseStatus.InternalServerError; } logger.trace("Constructed error response for the client - [{} - {}]", status, errReason); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); response.headers().set(HttpHeaderNames.DATE, new GregorianCalendar().getTime()); HttpUtil.setContentLength(response, 0); if (errReason != null) { response.headers().set(FAILURE_REASON_HEADER, errReason); } if (restServiceErrorCode != null && HttpStatusClass.CLIENT_ERROR.contains(status.code())) { response.headers().set(ERROR_CODE_HEADER, restServiceErrorCode.name()); } response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); boolean keepAlive = !forceClose && HttpUtil.isKeepAlive(responseMetadata) && request != null && !request.getRestMethod() .equals(RestMethod.POST) && !request.getRestMethod().equals(RestMethod.PUT) && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status); HttpUtil.setKeepAlive(response, keepAlive); return response; }