Mates, I am very new to kotlin and spring. I am trying to throw exepiion if record did not exist. I don't know the syntax how to wrap this line. So this is my exeption class:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Record not found")
class NotFound : Exception()
So here is my code :
fun getUserById(userId: Int): User {
return User(userRepository!!.findById(userId).orElse(ExeptionClass))//So the problem appears here
}
So it says that: classifier ExeptionClass does not have a companion object, and thus must be initialized here
So you want to throw an exception. You thus want to use orElseThrow(), and not orElse().
So you need to pass a supplier (i.e. a lambda) that creates and returns an exception, by invoking its constructor. And the exception is named NotFound, not ExeptionClass. So the code should be
return User(userRepository!!.findById(userId).orElseThrow { NotFound() })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With