com.linecorp.armeria.common.util.Exceptions.throwUnsafely()方法的使用及代码示例

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

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

Exceptions.throwUnsafely介绍

[英]Throws the specified exception violating the throws clause of the enclosing method. This method is useful when you need to rethrow a checked exception in Function, Consumer, Supplier and Runnable, only if you are sure that the rethrown exception will be handled as a Throwable or an Exception. For example:

CompletableFuture.supplyAsync(() -> catch (IOException e)  
// 'throw e;' won't work because Runnable.run() does not allow any checked exceptions. 
return Exceptions.throwUnsafely(e); 
} 
}).exceptionally(CompletionActions::log); 
}

[中]抛出违反封闭方法的Throws子句的指定异常。当您需要在Function、Consumer、Supplier和Runnable中重新显示选中的异常时,此方法非常有用,前提是您确定重新显示的异常将作为可丢弃或异常处理。例如:

CompletableFuture.supplyAsync(() -> catch (IOException e)  
// 'throw e;' won't work because Runnable.run() does not allow any checked exceptions. 
return Exceptions.throwUnsafely(e); 
} 
}).exceptionally(CompletionActions::log); 
}

代码示例

代码示例来源: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

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

代码示例来源: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

/**
 * 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);
  }
}

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

/**
 * Invokes the specified {@link Runnable} with {@link BouncyCastleKeyFactoryProvider} enabled temporarily.
 */
public static void call(Runnable task) {
  try {
    call(() -> {
      task.run();
      return true;
    });
  } catch (Exception e) {
    // It's safe to throw unsafely here because the Callable we passed never throws a checked exception.
    Exceptions.throwUnsafely(e);
  }
}

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

/**
 * Returns a bean resolver which retrieves a value using request converters. If the target element
 * is an annotated bean, a bean factory of the specified {@link BeanFactoryId} will be used for creating an
 * instance.
 */
private static BiFunction<AnnotatedValueResolver, ResolverContext, Object>
resolver(List<RequestObjectResolver> objectResolvers, BeanFactoryId beanFactoryId) {
  return (resolver, ctx) -> {
    Object value = null;
    for (final RequestObjectResolver objectResolver : objectResolvers) {
      try {
        value = objectResolver.convert(ctx, resolver.elementType(), beanFactoryId);
        break;
      } catch (FallthroughException ignore) {
        // Do nothing.
      } catch (Throwable cause) {
        Exceptions.throwUnsafely(cause);
      }
    }
    if (value != null) {
      return value;
    }
    throw new IllegalArgumentException("No suitable request converter found for a @" +
                      RequestObject.class.getSimpleName() + " '" +
                      resolver.elementType().getSimpleName() + '\'');
  };
}

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

@Nullable
  @Override
  public Credential apply(String keyName) {
    final CriteriaSet cs = new CriteriaSet();
    cs.add(new EntityIdCriterion(keyName));
    try {
      return resolver.resolveSingle(cs);
    } catch (Throwable cause) {
      return Exceptions.throwUnsafely(cause);
    }
  }
}

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

@Override
  public CloseableZooKeeper connection() {
    // Try up to three times to reduce flakiness.
    Throwable lastCause = null;
    for (int i = 0; i < 3; i++) {
      try {
        return ZooKeeperAssert.super.connection();
      } catch (Throwable t) {
        lastCause = t;
      }
    }

    return Exceptions.throwUnsafely(lastCause);
  }
}

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

@Override
  public O serve(ServiceRequestContext ctx, I req) throws Exception {
    return responseConverter.apply(
        strategy.accept(ctx, req).handleAsync((accept, thrown) -> {
          try {
            if (thrown != null || !accept) {
              return onFailure(ctx, req, thrown);
            }
            return onSuccess(ctx, req);
          } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
          }
        }, ctx.contextAwareEventLoop()));
  }
}

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

@Override
  public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    return HttpResponse.from(AuthorizerUtil.authorize(authorizer, ctx, req).handleAsync((result, cause) -> {
      try {
        if (cause == null) {
          if (result != null) {
            return result ? successHandler.authSucceeded(delegate(), ctx, req)
                   : failureHandler.authFailed(delegate(), ctx, req, null);
          }
          cause = AuthorizerUtil.newNullResultException(authorizer);
        }

        return failureHandler.authFailed(delegate(), ctx, req, cause);
      } catch (Exception e) {
        return Exceptions.throwUnsafely(e);
      }
    }, ctx.contextAwareEventLoop()));
  }
}

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

private void setNodeChild(Set<Endpoint> children) throws Throwable {
    try (CloseableZooKeeper zk = connection()) {
      // If the parent node does not exist, create it.
      if (!zk.exists(zNode).get()) {
        zk.create(zNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      }

      // Register all child nodes.
      children.forEach(endpoint -> {
        try {
          zk.create(zNode + '/' + endpoint.host() + '_' + endpoint.port(),
               NodeValueCodec.DEFAULT.encode(endpoint),
               Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (Exception e) {
          Exceptions.throwUnsafely(e);
        }
      });
    }
    children.forEach(endpoint -> assertExists(zNode + '/' + endpoint.host() + '_' + endpoint.port()));
  }
}

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

Exceptions.throwUnsafely((Throwable) result);
} else {
  assertThat(result).isEqualTo("OK");

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

return delegate().serve(ctx, req);
} catch (Exception e) {
  return Exceptions.throwUnsafely(e);

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

/**
 * Throws the specified {@link Throwable} if it is not {@code null}.
 */
static void throwUnsafelyIfNonNull(@Nullable Throwable cause) {
  if (cause != null) {
    Exceptions.throwUnsafely(cause);
  }
}

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

private static String urlDecode(String input) {
  try {
    // TODO(hyangtack) Remove this after https://github.com/line/armeria/issues/756 is resolved.
    return URLDecoder.decode(input, StandardCharsets.UTF_8.name());
  } catch (UnsupportedEncodingException e) {
    return Exceptions.throwUnsafely(e);
  }
}

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

private static Object handleWatchFailure(Throwable thrown) {
  if (Throwables.getRootCause(thrown) instanceof CancellationException) {
    // timeout happens
    return HttpResponse.of(HttpStatus.NOT_MODIFIED);
  }
  return Exceptions.throwUnsafely(thrown);
}

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

Revision normalize(Repository repository) {
  requireNonNull(repository, "repository");
  try {
    return repository.normalizeNow(Revision.HEAD);
  } catch (Throwable cause) {
    return Exceptions.throwUnsafely(cause);
  }
}

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

@SuppressWarnings("unchecked")
  static <T> T convertWithJackson(Entry<?> entry, Class<T> clazz) {
    requireNonNull(entry, "entry");
    requireNonNull(clazz, "clazz");
    try {
      return Jackson.treeToValue(((Entry<JsonNode>) entry).content(), clazz);
    } catch (Throwable cause) {
      return Exceptions.throwUnsafely(cause);
    }
  }
}

代码示例来源: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: com.linecorp.centraldogma/centraldogma-client-armeria-legacy-shaded

private static <T> CompletableFuture<T> run(ThriftCall<T> call) {
  final ThriftCompletableFuture<T> future = new ThriftCompletableFuture<>();
  try {
    call.apply(future);
    return future.exceptionally(cause -> Exceptions.throwUnsafely(convertCause(cause)));
  } catch (Exception e) {
    return CompletableFutures.exceptionallyCompletedFuture(convertCause(e));
  }
}

相关文章

微信公众号

最新文章

更多