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

The following examples show how to use io.vertx.ext.web.RoutingContext#failure() . These examples are extracted from open source projects. 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 Project: vertx-web   File: ErrorHandlerImpl.java    License: 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 2
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 3
protected void failureHandler(RoutingContext context) {
  LOGGER.error("http server failed.", context.failure());

  AbstractRestInvocation restProducerInvocation = context.get(RestConst.REST_PRODUCER_INVOCATION);
  Throwable e = context.failure();
  if (e instanceof ErrorDataDecoderException) {
    Throwable cause = e.getCause();
    if (cause instanceof InvocationException) {
      e = cause;
    }
  }

  // only when unexpected exception happens, it will run into here.
  // the connection should be closed.
  handleFailureAndClose(context, restProducerInvocation, e);
}
 
Example 4
@Test
public void failureHandlerNormal(@Mocked RoutingContext context) {
  RestProducerInvocation restProducerInvocation = new RestProducerInvocation();

  Exception e = new Exception();
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = restProducerInvocation;
      context.failure();
      returns(e, e);
      context.response();
      result = response;
    }
  };

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

  Assert.assertSame(e, this.throwable);
  Assert.assertTrue(response.responseClosed);
}
 
Example 5
@Test
public void failureHandlerErrorDataWithInvocation(@Mocked RoutingContext context, @Mocked InvocationException e) {
  RestProducerInvocation restProducerInvocation = new RestProducerInvocation();

  ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = restProducerInvocation;
      context.failure();
      returns(edde, edde);
      context.response();
      result = response;
    }
  };

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

  Assert.assertSame(e, this.throwable);
  Assert.assertTrue(response.responseClosed);
}
 
Example 6
@Test
public void failureHandlerErrorDataWithNormal(@Mocked RoutingContext context) {
  RestProducerInvocation restProducerInvocation = new RestProducerInvocation();

  Exception e = new Exception();
  ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = restProducerInvocation;
      context.failure();
      returns(edde, edde);
      context.response();
      result = response;
    }
  };

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

  Assert.assertSame(edde, this.throwable);
  Assert.assertTrue(response.responseClosed);
}
 
Example 7
@Test
public void failureHandlerWithNoRestProducerInvocationAndInvocationException(@Mocked RoutingContext context) {
  InvocationException e = new InvocationException(Status.REQUEST_ENTITY_TOO_LARGE, "testMsg");
  ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = null;
      context.failure();
      returns(edde, edde);
      context.response();
      result = response;
    }
  };

  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.assertThat(response.responseStatusMessage, Matchers.is(Status.REQUEST_ENTITY_TOO_LARGE.getReasonPhrase()));
  Assert.assertThat(response.responseChunk,
      Matchers.is("{\"message\":\"" + Status.REQUEST_ENTITY_TOO_LARGE.getReasonPhrase() + "\"}"));
  Assert.assertTrue(response.responseEnded);
}
 
Example 8
@Test
public void failureHandlerWithNoRestProducerInvocationAndOtherException(@Mocked RoutingContext context) {
  String exceptionMessage = "test exception message";
  Exception exception = new Exception(exceptionMessage);
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = null;
      context.failure();
      returns(exception, exception);
      context.response();
      result = response;
    }
  };

  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.responseChunk,
      Matchers.is("{\"message\":\"" + exceptionMessage + "\"}"));
  Assert.assertTrue(response.responseEnded);
}
 
Example 9
@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 10
@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 11
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 12
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 13
Source Project: ethsigner   File: JsonRpcErrorHandler.java    License: 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 14
Source Project: xyz-hub   File: XYZHubRESTVerticle.java    License: 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 15
protected void onFailure(RoutingContext context) {
  LOGGER.error("edge server failed.", context.failure());
  HttpServerResponse response = context.response();
  if (response.closed() || response.ended()) {
    return;
  }

  if (context.failure() instanceof InvocationException) {
    InvocationException exception = (InvocationException) context.failure();
    response.setStatusCode(exception.getStatusCode());
    response.setStatusMessage(exception.getReasonPhrase());
    if (null == exception.getErrorData()) {
      response.end();
      return;
    }

    String responseBody;
    try {
      responseBody = RestObjectMapperFactory.getRestObjectMapper().writeValueAsString(exception.getErrorData());
      response.putHeader("Content-Type", MediaType.APPLICATION_JSON);
    } catch (JsonProcessingException e) {
      responseBody = exception.getErrorData().toString();
      response.putHeader("Content-Type", MediaType.TEXT_PLAIN);
    }
    response.end(responseBody);
  } else {
    response.setStatusCode(Status.BAD_GATEWAY.getStatusCode());
    response.setStatusMessage(Status.BAD_GATEWAY.getReasonPhrase());
    response.end();
  }
}
 
Example 16
Source Project: mpns   File: ApiErrorHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
    Throwable e = rc.failure();
    int code = 500;
    String message = null;
    if (e instanceof ApiException) {
        ApiException apiException = (ApiException) e;
        code = apiException.getCode();
        message = apiException.getMessage();
    }

    rc.response().end(new ApiResult<>(code, message).toString());

    logger.error("api error, code={}, msg={}", code, message, e);
}
 
Example 17
Source Project: nubes   File: DefaultErrorHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  Throwable cause = context.failure();
  HttpServerResponse response = context.response();
  String contentType = ContentTypeProcessor.getContentType(context);
  PayloadMarshaller marshaller = marshallers.get(contentType);
  if (cause != null) {
    handleErrorWithCause(context, cause, response, contentType, marshaller);
  } else {
    handleHttpError(context, response, marshaller);
  }
}
 
Example 18
Source Project: orion   File: HttpErrorHandler.java    License: Apache License 2.0 4 votes vote down vote up
private boolean hasError(final RoutingContext failureContext) {
  return failureContext.failure() != null;
}
 
Example 19
@Test
public void onFailure(@Mocked RoutingContext context) {
  Map<String, Object> map = new HashMap<>();
  HttpServerResponse response = new MockUp<HttpServerResponse>() {
    @Mock
    HttpServerResponse setStatusCode(int statusCode) {
      map.put("code", statusCode);
      return null;
    }

    @Mock
    HttpServerResponse setStatusMessage(String statusMessage) {
      map.put("msg", statusMessage);
      return null;
    }
  }.getMockInstance();

  new Expectations() {
    {
      context.failure();
      returns(new RuntimeExceptionWithoutStackTrace("failed"), null);
      context.response();
      result = response;
    }
  };

  AbstractEdgeDispatcherForTest dispatcher = new AbstractEdgeDispatcherForTest();
  dispatcher.onFailure(context);

  Assert.assertEquals(502, map.get("code"));
  Assert.assertEquals("Bad Gateway", map.get("msg"));

  new Expectations() {
    {
      context.failure();
      returns(new InvocationException(401, "unauthorized", "unauthorized"),
          new InvocationException(401, "unauthorized", "unauthorized"));
      context.response();
      result = response;
    }
  };

  dispatcher = new AbstractEdgeDispatcherForTest();
  dispatcher.onFailure(context);

  Assert.assertEquals(401, map.get("code"));
  Assert.assertEquals("unauthorized", map.get("msg"));
}
 
Example 20
private boolean oauth2Error(RoutingContext context) {
    return context.failed() && context.failure() instanceof OAuth2Exception;
}