Home > Software design >  how to handle hibernate.exception in springboot by kotlin?
how to handle hibernate.exception in springboot by kotlin?

Time:09-26

If i try to create a duplicate ID, the following error occurs:

{
    "messages": [
        "could not execute statement; SQL [n/a]; constraint [user.UK_6ntlp6n5ltjg6hhxl66jj5u0l]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
    ],
    "timestamp": "2022-09-23T15:57:55.545009"
}

I want to customize this error, how do I do it? Can you show me a simple example?

My code is below.

@Service
class UserService(
    private val userRepository: UserRepository
) {
    fun userRegister(inData: UserRegisterReq): User {
        return userRepository.save(inData.getUser())
    }
}

I am using springBoot of kotlin.

I'm a beginner, sorry.

the desired shape

{
    "message" : [ "This is a duplicate user", ]
}

CodePudding user response:

    @Service
    class UserService(
        private val userRepository: UserRepository
    ) {
        fun userRegister(inData: UserRegisterReq):Any {

           return  try{
             userRepository.save(inData.getUser())
                     }
          catch(e:Exception){
         "This is a duplicate user"
                     }
        }
    }

You can use Try and catch as above. Rather than capturing Exception capturing constraint Violation Exception is better. Also can use multiple catch blocks. ( This is the simplest solution for your problem)

  • Related