com.linecorp.armeria.common.util.Exceptions类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(9.8k)|赞(0)|评价(0)|浏览(112)

本文整理了Java中com.linecorp.armeria.common.util.Exceptions类的一些代码示例,展示了Exceptions类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Exceptions类的具体详情如下:
包路径:com.linecorp.armeria.common.util.Exceptions
类名称:Exceptions

Exceptions介绍

[英]Provides methods that are useful for handling exceptions.
[中]提供用于处理异常的方法。

代码示例

代码示例来源:origin: line/armeria

@Nullable
private static String handleThrowable(@Nullable Throwable cause) {
  if (cause == null) {
    return null;
  }
  cause = Exceptions.peel(cause);
  final String message = cause.getMessage();
  return message != null ? cause.getClass().getSimpleName() + ": " + message
              : cause.getClass().getSimpleName();
}

代码示例来源:origin: line/armeria

/**
 * Creates a {@link SamlEndpoint} of the specified {@code uri} and the HTTP POST binding protocol.
 */
public static SamlEndpoint ofHttpPost(String uri) {
  requireNonNull(uri, "uri");
  try {
    return ofHttpPost(new URI(uri));
  } catch (URISyntaxException e) {
    return Exceptions.throwUnsafely(e);
  }
}

代码示例来源:origin: line/armeria

@Test
public void maxInboundSize_tooBig() throws Exception {
  final StreamingOutputCallRequest request =
      StreamingOutputCallRequest.newBuilder()
                   .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                   .build();
  final int size = blockingStub.streamingOutputCall(request).next().getSerializedSize();
  requestLogQueue.take();
  final TestServiceBlockingStub stub =
      Clients.newDerivedClient(
          blockingStub,
          GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES.newValue(size - 1));
  final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
  assertThat(t).isInstanceOf(StatusRuntimeException.class);
  assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
  assertThat(Exceptions.traceText(t)).contains("exceeds maximum");
  checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
    assertThat(rpcReq.params()).containsExactly(request);
    assertThat(grpcStatus).isNotNull();
    assertThat(grpcStatus.getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
  });
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

static HttpResponse handleException(ServiceRequestContext ctx, Throwable cause) {
  cause = Exceptions.peel(cause);
  if (cause instanceof RepositoryNotFoundException ||
    cause instanceof ProjectNotFoundException) {
    return HttpApiUtil.newResponse(ctx, HttpStatus.NOT_FOUND, cause);
  } else {
    return Exceptions.throwUnsafely(cause);
  }
}

代码示例来源:origin: line/armeria

@Nonnull
  private static FileServiceException newFileServiceException() {
    // Remove the stack trace so we do not pollute the build log.
    return Exceptions.clearTrace(new FileServiceException());
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

static HttpResponse handleException(Throwable cause) {
  cause = Exceptions.peel(cause);
  if (cause instanceof RepositoryNotFoundException ||
    cause instanceof ProjectNotFoundException) {
    return HttpApiUtil.newResponse(HttpStatus.NOT_FOUND, cause);
  } else {
    return Exceptions.throwUnsafely(cause);
  }
}

代码示例来源:origin: line/armeria

@Override
  public void unaryCall(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
    IllegalStateException e1 = new IllegalStateException("Exception 1");
    IllegalArgumentException e2 = new IllegalArgumentException();
    AssertionError e3 = new AssertionError("Exception 3");
    Exceptions.clearTrace(e3);
    RuntimeException e4 = new RuntimeException("Exception 4");
    e1.initCause(e2);
    e2.initCause(e3);
    e3.initCause(e4);
    Status status = Status.ABORTED.withCause(e1);
    responseObserver.onError(status.asRuntimeException());
  }
}

代码示例来源:origin: line/armeria

private HttpFile cache() {
  // TODO(trustin): We assume here that the file being read is small enough that it will not block
  //                an event loop for a long time. Revisit if the assumption turns out to be false.
  AggregatedHttpFile cachedFile = null;
  try {
    this.cachedFile = cachedFile = file.aggregate(MoreExecutors.directExecutor()).get();
  } catch (Exception e) {
    this.cachedFile = null;
    logger.warn("Failed to cache a file: {}", file, Exceptions.peel(e));
  }
  return MoreObjects.firstNonNull(cachedFile, file);
}

代码示例来源:origin: line/centraldogma

static HttpResponse handleException(ServiceRequestContext ctx, Throwable cause) {
  cause = Exceptions.peel(cause);
  if (cause instanceof RepositoryNotFoundException ||
    cause instanceof ProjectNotFoundException) {
    return HttpApiUtil.newResponse(ctx, HttpStatus.NOT_FOUND, cause);
  } else {
    return Exceptions.throwUnsafely(cause);
  }
}

代码示例来源:origin: line/armeria

private HttpData toJsonHttpData(@Nullable Object value) {
  try {
    return HttpData.of(mapper.writeValueAsBytes(value));
  } catch (Exception e) {
    return Exceptions.throwUnsafely(e);
  }
}

代码示例来源:origin: line/armeria

errorRes = HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR,
                MediaType.PLAIN_TEXT_UTF_8,
                Exceptions.traceText(cause));
} else {
  errorRes = HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);

代码示例来源:origin: line/armeria

@Test
public void testIdentity_FileService_create_exception() throws Exception {
  final FileService.Client client = new FileService.Client.Factory().getClient(inProto, outProto);
  client.send_create(BAZ);
  assertThat(out.length()).isGreaterThan(0);
  final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
  final THttpService syncService = THttpService.of((FileService.Iface) path -> {
    throw exception;
  }, defaultSerializationFormat);
  final THttpService asyncService = THttpService.of(
      (FileService.AsyncIface) (path, resultHandler) ->
          resultHandler.onError(exception), defaultSerializationFormat);
  invokeTwice(syncService, asyncService);
  assertThat(promise.get()).isEqualTo(promise2.get());
}

代码示例来源:origin: line/armeria

/**
 * A {@link RetryStrategy} that retries only on {@link UnprocessedRequestException} with the specified
 * {@link Backoff}.
 */
static RetryStrategy onUnprocessed(Backoff backoff) {
  requireNonNull(backoff, "backoff");
  return onStatus((status, thrown) -> {
    if (thrown != null && Exceptions.peel(thrown) instanceof UnprocessedRequestException) {
      return backoff;
    }
    return null;
  });
}

代码示例来源:origin: line/centraldogma

private static void commitProjectMetadata(RepositorySupport<ProjectMetadata> metadataRepo,
                     CommandExecutor executor, String projectName,
                     ProjectMetadata metadata) {
  try {
    executor.execute(createRepository(author, projectName, Project.REPO_DOGMA)).join();
  } catch (Throwable cause) {
    cause = Exceptions.peel(cause);
    if (!(cause instanceof RepositoryExistsException)) {
      Exceptions.throwUnsafely(cause);
    }
  }
  try {
    metadataRepo.push(projectName, Project.REPO_DOGMA, author,
             "Add the metadata file",
             Change.ofJsonUpsert(METADATA_JSON, Jackson.valueToTree(metadata)))
          .toCompletableFuture().join();
    logger.info("Project '{}' has been migrated", projectName);
  } catch (Throwable cause) {
    cause = Exceptions.peel(cause);
    if (!(cause instanceof RedundantChangeException)) {
      Exceptions.throwUnsafely(cause);
    }
  }
}

代码示例来源:origin: line/armeria

private HttpData toJsonSequencesHttpData(@Nullable Object value) {
    try {
      final ByteArrayOutputStream out = new ByteArrayOutputStream();
      out.write(RECORD_SEPARATOR);
      mapper.writeValue(out, value);
      out.write(LINE_FEED);
      return HttpData.of(out.toByteArray());
    } catch (Exception e) {
      return Exceptions.throwUnsafely(e);
    }
  }
}

代码示例来源:origin: line/armeria

@Test
public void maxOutboundSize_tooBig() throws Exception {
  // set at least one field to ensure the size is non-zero.
  final StreamingOutputCallRequest request =
      StreamingOutputCallRequest.newBuilder()
                   .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                   .build();
  final TestServiceBlockingStub stub =
      Clients.newDerivedClient(
          blockingStub,
          GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES.newValue(
              request.getSerializedSize() - 1));
  final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
  assertThat(t).isInstanceOf(StatusRuntimeException.class);
  assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.CANCELLED);
  assertThat(Exceptions.traceText(t)).contains("message too large");
  checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
    assertThat(rpcReq.params()).containsExactly(request);
    assertThat(grpcStatus).isNotNull();
    assertThat(grpcStatus.getCode()).isEqualTo(Code.CANCELLED);
  });
}

代码示例来源:origin: line/armeria

@Test
public void testSync_FileService_create_exception() throws Exception {
  final FileService.Client client = new FileService.Client.Factory().getClient(inProto, outProto);
  client.send_create(BAZ);
  assertThat(out.length()).isGreaterThan(0);
  final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
  final THttpService service = THttpService.of((FileService.Iface) path -> {
    throw exception;
  }, defaultSerializationFormat);
  invoke(service);
  try {
    client.recv_create();
    fail(TApplicationException.class.getSimpleName() + " not raised.");
  } catch (TApplicationException e) {
    assertThat(e.getType()).isEqualTo(TApplicationException.INTERNAL_ERROR);
    assertThat(e.getMessage()).contains(exception.toString());
  }
}

代码示例来源:origin: line/armeria

@Override
public synchronized void stop() {
  try {
    if (isRunning) {
      server.stop().get();
      isRunning = false;
    }
  } catch (Exception cause) {
    throw new WebServerException("Failed to stop " + ArmeriaWebServer.class.getSimpleName(),
                   Exceptions.peel(cause));
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

private static void commitProjectMetadata(RepositorySupport<ProjectMetadata> metadataRepo,
                     CommandExecutor executor, String projectName,
                     ProjectMetadata metadata) {
  try {
    executor.execute(createRepository(author, projectName, Project.REPO_DOGMA)).join();
  } catch (Throwable cause) {
    cause = Exceptions.peel(cause);
    if (!(cause instanceof RepositoryExistsException)) {
      Exceptions.throwUnsafely(cause);
    }
  }
  try {
    metadataRepo.push(projectName, Project.REPO_DOGMA, author,
             "Add the metadata file",
             Change.ofJsonUpsert(METADATA_JSON, Jackson.valueToTree(metadata)))
          .toCompletableFuture().join();
    logger.info("Project '{}' has been migrated", projectName);
  } catch (Throwable cause) {
    cause = Exceptions.peel(cause);
    if (!(cause instanceof RedundantChangeException)) {
      Exceptions.throwUnsafely(cause);
    }
  }
}

代码示例来源:origin: line/armeria

/**
 * Creates a {@link SamlEndpoint} of the specified {@code uri} and the HTTP Redirect binding protocol.
 */
public static SamlEndpoint ofHttpRedirect(String uri) {
  requireNonNull(uri, "uri");
  try {
    return ofHttpRedirect(new URI(uri));
  } catch (URISyntaxException e) {
    return Exceptions.throwUnsafely(e);
  }
}

相关文章