我尝试使用 GraphQL 和 Kotlin 开发 REST API,但面临以下问题:我尝试创建一个扩展 RuntimeException 并实现 GraphQLError 的自定义异常,但在 Kotlin 中我无法执行此操作,因为我收到了此消息: Accidental override when using third party Java interface and extending RuntimeException in kotlin .
我通过为 CustomException 创建一个 Java 类来解决此问题。
但我不知道为什么,当我创建一个扩展 RuntimeException
并实现 GraphQLError
的 kotlin 类时,我需要重写 getMessage()
方法来自 GraphQLError,但是当我创建一个扩展 RuntimeException 并实现 GraphQLError 的 java 类时,我不需要重写来自 GraphQLError 的 getMessage()
方法。
谢谢!
最佳答案
使用 @JvmField 注释消息,例如:
class MyError(@JvmField override val message: String?, private val invalidField: String? = null) : RuntimeException(message), GraphQLError {
override fun getMessage(): String = super.message ?: "no error message set"
override fun getLocations(): List<SourceLocation> = emptyList()
override fun getErrorType(): ErrorType = ErrorType.DataFetchingException
override fun getExtensions(): Map<String, Any> = if(invalidField!=null)
Collections.singletonMap<String, Any>("invalidField", invalidField)
else
Collections.emptyMap()
}
关于java - Kotlin 和 Java 中的 RuntimeException 和 GraphQLError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51185242/