Java Code Examples for io.vertx.ext.web.RoutingContext#statusCode()

The following examples show how to use io.vertx.ext.web.RoutingContext#statusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApiVerticle.java    From gushici with GNU General Public License v3.0 6 votes vote down vote up
private void returnError(RoutingContext routingContext) {
    JsonObject result = new JsonObject();
    int errorCode = routingContext.statusCode() > 0 ? routingContext.statusCode() : 500;
    // 不懂 Vert.x 为什么 EventBus 和 Web 是两套异常系统
    if (routingContext.failure() instanceof ReplyException) {
        errorCode = ((ReplyException) routingContext.failure()).failureCode();
    }
    result.put("error-code", errorCode);
    if (routingContext.failure() != null) {
        result.put("reason", routingContext.failure().getMessage());
    }
    setCommonHeader(routingContext.response()
        .setStatusCode(errorCode)
        .putHeader("content-type", "application/json; charset=utf-8"))
        .end(result.encodePrettily());
}
 
Example 2
Source File: TestVertxRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerWithNoExceptionAndStatusCodeIsSet(@Mocked RoutingContext context) {
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = null;
      context.failure();
      returns(null, null);
      context.response();
      result = response;
      context.statusCode();
      result = Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode();
    }
  };

  Deencapsulation.invoke(dispatcher, "failureHandler", context);

  Assert.assertThat(response.responseHeader, Matchers.hasEntry(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD));
  Assert.assertThat(response.responseStatusCode, Matchers.is(Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode()));
  Assert.assertTrue(response.responseEnded);
}
 
Example 3
Source File: TestVertxRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerWithNoExceptionAndStatusCodeIsNotSet(@Mocked RoutingContext context) {
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = null;
      context.failure();
      returns(null, null);
      context.response();
      result = response;
      context.statusCode();
      result = Status.OK.getStatusCode();
    }
  };

  Deencapsulation.invoke(dispatcher, "failureHandler", context);

  Assert.assertThat(response.responseHeader, Matchers.hasEntry(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD));
  Assert.assertThat(response.responseStatusCode, Matchers.is(Status.INTERNAL_SERVER_ERROR.getStatusCode()));
  Assert.assertThat(response.responseStatusMessage, Matchers.is(Status.INTERNAL_SERVER_ERROR.getReasonPhrase()));
  Assert.assertThat(response.responseChunk,
      Matchers.is("{\"message\":\"" + Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\"}"));
  Assert.assertTrue(response.responseEnded);
}
 
Example 4
Source File: ApiController.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
private void failureHandler(RoutingContext rc) {
  logger.info("An error whilst processing request {}", rc.normalisedPath());

  Throwable requestFailure = rc.failure();
  if (requestFailure != null) {
    HttpServerResponse response = rc.response();
    if (isBadRequest(requestFailure)) {
      logger.info("Request error:", requestFailure);
      response.setStatusCode(HTTP_BAD_REQUEST);
    } else {
      logger.error("Internal error", requestFailure);
      response.setStatusCode(HTTP_INTERNAL_ERROR);
    }
    String description = Strings.nullToEmpty(requestFailure.getMessage());
    response.putHeader(CONTENT_TYPE, "text/plain")
        .end(description);
  } else {
    int failureStatusCode = rc.statusCode();
    rc.response()
        .setStatusCode(failureStatusCode)
        .end();
  }
}
 
Example 5
Source File: ApiController.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
private void failureHandler(RoutingContext rc) {
  logger.info("An error whilst processing request {}", rc.normalisedPath());

  Throwable requestFailure = rc.failure();
  if (requestFailure != null) {
    Optional<String> badRequest = badRequestDescription(requestFailure);
    if (badRequest.isPresent()) {
      rc.response()
          .setStatusCode(HTTP_BAD_REQUEST)
          .end(badRequest.get());
    } else {
      logger.error("Request error:", requestFailure);
      rc.response()
          .setStatusCode(HTTP_INTERNAL_ERROR)
          .end();
    }
  } else {
    int failureStatusCode = rc.statusCode();
    rc.response()
        .setStatusCode(failureStatusCode)
        .end();
  }
}
 
Example 6
Source File: ErrorHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {

  HttpServerResponse response = context.response();

  Throwable failure = context.failure();

  int errorCode = context.statusCode();
  String errorMessage = null;
  if (errorCode != -1) {
    context.response().setStatusCode(errorCode);
    errorMessage = context.response().getStatusMessage();
  } else {
    errorCode = 500;
    if (displayExceptionDetails) {
      errorMessage = failure.getMessage();
    }
    if (errorMessage == null) {
      errorMessage = "Internal Server Error";
    }
    // no new lines are allowed in the status message
    response.setStatusMessage(errorMessage.replaceAll("\\r|\\n", " "));
  }

  answerWithError(context, errorCode, errorMessage);
}
 
Example 7
Source File: JsonRpcErrorHandler.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
  final Optional<JsonRpcRequest> jsonRpcRequest = jsonRpcRequest(context);
  final JsonRpcErrorResponse errorResponse = errorResponse(context, jsonRpcRequest);
  final int statusCode =
      context.statusCode() == -1 ? INTERNAL_SERVER_ERROR.code() : context.statusCode();
  LOG.debug(
      "Failed to correctly handle request. method: {}, uri: {}, body: {}, Error body: {}",
      context.request()::method,
      context.request()::absoluteURI,
      () -> jsonRpcRequest.map(Json::encodePrettily).orElse(context.getBodyAsString()),
      () -> Json.encode(errorResponse),
      () -> context.failure());
  httpResponseFactory.create(context.request(), statusCode, errorResponse);
}
 
Example 8
Source File: JsonRpcErrorHandler.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private JsonRpcError jsonRpcError(final RoutingContext context) {
  if (context.failure() instanceof JsonRpcException) {
    final JsonRpcException jsonRpcException = (JsonRpcException) context.failure();
    return jsonRpcException.getJsonRpcError();
  } // in case of a timeout we may not have a failure exception so we use the status code
  else if (context.statusCode() == BAD_GATEWAY.code()) {
    return FAILED_TO_CONNECT_TO_DOWNSTREAM_NODE;
  } else if (context.statusCode() == GATEWAY_TIMEOUT.code()) {
    return CONNECTION_TO_DOWNSTREAM_NODE_TIMED_OUT;
  } else {
    return INTERNAL_ERROR;
  }
}
 
Example 9
Source File: XYZHubRESTVerticle.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private static void failureHandler(RoutingContext context) {
  if (context.failure() != null) {
    sendErrorResponse(context, context.failure());
  } else {
    String message = context.statusCode() == 401 ? "Missing auth credentials." : "A failure occurred during the execution.";
    HttpResponseStatus status = context.statusCode() >= 400 ? HttpResponseStatus.valueOf(context.statusCode()) : INTERNAL_SERVER_ERROR;
    sendErrorResponse(context, new HttpException(status, message));
  }
}
 
Example 10
Source File: HttpErrorHandler.java    From orion with Apache License 2.0 5 votes vote down vote up
private Buffer errorJson(final RoutingContext failureContext) {
  final OrionErrorCode orionError = orionError(failureContext.failure());
  final HttpError httpError = new HttpError(orionError);
  final Buffer buffer = Buffer.buffer(Serializer.serialize(HttpContentType.JSON, httpError));

  if (failureContext.statusCode() == 404) {
    // To reduce noise 404s are only logged as debug. A 404 is returned for the common use case where Besu receives a
    // private marker transaction for a privacy group that this Orion is not part of.
    log.debug("Not Found Error: \"" + orionError + "\" Body: \"" + failureContext.getBodyAsString() + "\"");
  } else {
    log.error(failureContext.currentRoute().getPath() + " failed " + httpError, failureContext.failure());
  }
  return buffer;
}
 
Example 11
Source File: DefaultErrorHandler.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void handleHttpError(RoutingContext context, HttpServerResponse response, PayloadMarshaller marshaller) {
  final int status = context.statusCode();
  response.setStatusCode(status);
  String msg = errorMessages.getOrDefault(status, "Internal server error");
  if (context.get(ERROR_DETAILS) != null) {
    msg = context.get(ERROR_DETAILS);
  }
  if (marshaller != null) {
    response.end(marshaller.marshallHttpStatus(status, msg));
  } else {
    if (!response.ended()) {
      response.end(msg);
    }
  }
}
 
Example 12
Source File: HttpErrorHandler.java    From orion with Apache License 2.0 4 votes vote down vote up
/**
 * Status code may not have been set (left as a negative number), in which case assume server side issue.
 */
private int statusCode(final RoutingContext failureContext) {
  return failureContext.statusCode() < 0 ? HttpResponseStatus.INTERNAL_SERVER_ERROR.code()
      : failureContext.statusCode();
}