Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 661
Lucas Andrade Avatar asked Oct 16 '25 00:10

Lucas Andrade


2 Answers

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

like image 157
Makoto Avatar answered Oct 18 '25 12:10

Makoto


Just one trick, if you want to avoid the return statement you can update your method to use "the kotlin full powers"

Something like this:

fun findById(id: Long): User = 
    userRepository.findById(id)
        ?.let { it.orElseThrow(HttpStatusException(HttpStatus.NOT_FOUND, "User not found"))}

This is a use for safe-call operator and the transformation method let that get your entity or throw an Exception if not found it.

like image 29
rflpazini Avatar answered Oct 18 '25 14:10

rflpazini



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!