Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classifier does not have a companion object , and thus must be initialized here

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

like image 727
Чынгыз Усенов Avatar asked Dec 13 '25 13:12

Чынгыз Усенов


1 Answers

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() })
like image 199
JB Nizet Avatar answered Dec 16 '25 23:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!