【发布时间】:2019-12-29 11:20:17
【问题描述】:
伙计们,我对 kotlin 和 spring 很陌生。如果记录不存在,我试图抛出 exepiion。我不知道如何包装这一行的语法。 所以这是我的例外类:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Record not found")
class NotFound : Exception()
这是我的代码:
fun getUserById(userId: Int): User {
return User(userRepository!!.findById(userId).orElse(ExeptionClass))//So the problem appears here
}
所以它说:分类器 ExeptionClass 没有伴生对象,因此必须在这里初始化
【问题讨论】:
-
什么是
ExeptionClass?你想达到什么目的? -
当我尝试获取不存在的 ID 时,我希望出现异常。
-
离题:Java 的
Optional在 Kotlin 中没用,最好在你的 repo 中创建一个方法:fun findById(id:Int): User?。然后只使用可空类型而不是可选类型:repo.findById(id) ?: ExeptionClass()。另外要摆脱那些!!,您必须通过使用不可为空类型的构造函数注入 repo。