分类器没有伴随对象,因此必须在此处初始化

时间:2019-08-24 12:40:56

标签: java spring kotlin

伴侣,我对Kotlin和Spring非常陌生。如果记录不存在,我将尝试引起怀疑。我不知道语法如何换行。 这是我的exeption类:

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没有伴随对象,因此必须在此处初始化

1 个答案:

答案 0 :(得分:1)

因此您想抛出异常。因此,您要使用orElseThrow(),而不是orElse()

因此,您需要通过调用构造函数传递创建并返回异常的供应商(即lambda)。并且该异常名为NotFound,而不是ExeptionClass。所以代码应该是

return User(userRepository!!.findById(userId).orElseThrow { NotFound() })