【发布时间】:2020-10-02 17:05:25
【问题描述】:
我正在使用 Kotlin 开发 Micronaut gRPC 服务器。默认情况下,如果我的 gRPC 端点抛出异常,它会在没有任何日志记录的情况下被吞下(即使在调试级别),并且 gRPC 仅返回 status: UNKNOWN 错误响应,没有详细信息。
我希望我的所有 gRPC 端点都在 ERROR 级别记录任何未捕获的异常及其堆栈跟踪。我怎样才能做到这一点?我可以看到使用 Micronaut 服务工具(拦截/记录异常)、一些 gRPC 更改或仅在 Kotlin 语言级别解决此问题,以有效地将相同的除日志重新抛出逻辑应用于所有端点功能。
这是我尝试过的以及我发现的其他文档:
作为一种解决方法,我添加了一个用于登录我的端点的 try-catch,但我不想在每个端点中都有这个样板;我认为有一些更有效的方法可以将它添加到拦截器或其他东西中,但在 Micronaut 文档中没有找到。
import mu.KotlinLogging
import javax.inject.Singleton
import javax.sql.DataSource
private val logger = KotlinLogging.logger {}
@Singleton
@Suppress("unused")
class MyEndpoint(val dataSource: DataSource) : MyServiceGrpcKt.MyServiceCoroutineImplBase() {
override suspend fun search(request: MyRequest): MyResponse {
try {
dataSource.getConnection().use { con ->
con.prepareStatement("SELECT ... some sql ... ").use { stm ->
stm.setString(1, request.query)
stm.executeQuery().use { rs ->
// build RPC response from ResultSet
}
}
}
}
} catch (e: Throwable) {
// The question is, how to avoid having to add this try-catch and logger.error
// call in every Endpoint?
logger.error(e) { "Error handling $request" }
throw e
}
return MyResponse.newBuilder().setStuff(... from sql ...).build()
}
}
我检查了Micronaut gRPC server docs 和gRPC error handling guide,但没有看到提示。 Micronaut error handling docs 用于 HTTP 错误页面,而不是通用拦截器。我也在gitter Micronaut community上问过,没有回应。
gRPC Endpoint 类的抽象基础确实在我正在实现的 search RPC 方法上有这个文档:
/**
* Returns the response to an RPC for valohealth_monocle.model_search.ModelSearchService.Search.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [io.grpc.Status]. If this method fails with a [java.util.concurrent.CancellationException],
* the RPC will fail
* with status `Status.CANCELLED`. If this method fails for any other reason, the RPC will
* fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun search...
该注释表明 gRPC 将异常转换为 UNKNOWN 状态是预期的行为。但它并没有指出我如何启用捕获异常的日志记录。
【问题讨论】:
标签: kotlin micronaut grpc-java