Search code examples
javaspring-bootkotlinmicronaut

Exception handling in Micronaut


Is there a way in micronaut to throw an exception that will specify the error code for the response, in the same way we can do in springboot:

throw new ResponseStatusException(HttpStatus.FORBIDDEN)

or do we always have to implement our own exception handler?

I would rather not have to implement exception handers just to be able to return a 400 or 403 response.


Solution

  • The class I wanted is:

    io.micronaut.http.exceptions.HttpStatusException
    

    I did not find it at first because I was missing the dependency:

    implementation("io.micronaut:micronaut-http")
    

    I am using it to successfully return a 404 error with a message in this example:

    fun findById(id: Long): User {
        val user = userRepository.findById(id)
        return if (user.isPresent()) user.get() else throw HttpStatusException(HttpStatus.NOT_FOUND, "User not found")
    }
    

    Feel free to comment if this is decent kotlin code. I am quite new to kotlin, from a java and scala background. Looks decent to me xD