如何解决Micronaut gRPC服务器端点包含异常gRPC的StatusException除外;如何记录它们呢?
我正在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,创建一个ServerInterceptor
like this。请注意,这与how it's done in grpc-java
不同。
在Micronaut中,只需将类注释为@javax.inject.Singleton
即可安装拦截器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。