Reputation: 195
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.
Upvotes: 4
Views: 4996
Reputation: 23
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.
Upvotes: 1
Reputation: 106460
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
Upvotes: 4