Affects: Spring Boot 3.2.3
Library: Kotlin Serialization 1.9.23
Overview: Kotlin serialization problem occuring in ResponseEntityExceptionHandler.java
class.
Code
The exception controller advice:
@ControllerAdvice
class ExceptionControllerAdvice: ResponseEntityExceptionHandler() {
@ExceptionHandler(value = [InternalError::class])
fun handleInternalError(error: InternalError, request: WebRequest): ResponseEntity<*> {
TODO("Log it and create a warning")
}
@ExceptionHandler(value = [DefinitionException::class])
fun handleDefinitionException(exception: DefinitionException): ResponseEntity<DefinitionException> {
return ResponseEntity.status(exception.httpCode).body(exception)
}
}
The serializer config:
val GLOBAL_JSON = Json {
serializersModule = SerializersModule {
include(DEFINITION_EXCEPTION_SERIALIZERS_MODULE)
}
}
@Configuration
@EnableWebMvc
class WebMvcConfiguration: WebMvcConfigurer {
private val converter = KotlinSerializationJsonHttpMessageConverter(GLOBAL_JSON)
override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
converters.add(this.converter)
}
}
The test:
@Test fun `name contains too many characters`() {
val name = name + UUID.randomUUID()
val url = "${ProfileController.HTTP_ROUTE}/$name/create"
mvc.post(url) {
accept = MediaType.ALL
}.andExpectAll {
status { isNotAcceptable() }
content { json(
"""
{
}
""".trimIndent(), true) }
}
}
Error
When I run the code and a Definition exception is thrown I get this error:
org.springframework.web.HttpMediaTypeNotAcceptableException: No acceptable representation
Expected Behaviour
It should serialize my exception with no problem.
What is weird is that I can actually serialize my class using Json#encodeToString
directly but when it comes to my controller I get an error from my test when I set as the return type the sealed class and not the class itself.
(If you need any more code feel free to ask, thanks for reading.)
Comment From: snicoll
Why do you have @EnableWebMvc
there? If you're using Spring Boot it switches off all the auto-configuration for Spring MVC.
(If you need any more code feel free to ask, thanks for reading.)
Actually, we're not very fan of code in text as we don't find them very actionable. Can you please edit your description to move all of that and replace it with a link to a small sample we can run.
Comment From: Pseudow
Hi thank for your answer, I just tried to create a single "actionable" class which resulted in a success. I guess it is a problem related to my setup and not Spring directly.