I'm new to Spring Boot. In my Controller I'm using UUID
s as @PathVariable
. By default spring returns MethodArgumentTypeMismatchException
when passing an invalid UUID
.
When the client passes an invalid UUID
I want to throw a custom InvalidUUIDException
, so that I'm able to return a customized ErrorDto using this Exception.
To archieve that I'm trying to register a custom UUIDConverter
(implementing org.springframework.core.convert.converter.Converter
).
@Component
public class UUIDConverter implements Converter<String, UUID>
{
private static final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
@Override
public UUID convert(String input) throws InvalidUuidException
{
if (!pattern.matcher(input).matches()) {
throw new InvalidUuidException(input);
}
return UUID.fromString(input);
}
}
To register this component, I'm adding this Converter to springs ConversionService
. Using the ConversionServiceFactoryBean
.
@Configuration
public class ConversionServiceConfiguration
{
@Bean
public ConversionServiceFactoryBean conversionService()
{
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(getConverters());
return bean;
}
private Set<Converter> getConverters()
{
Set<Converter> converters = new HashSet<>();
converters.add(new UUIDConverter());
return converters;
}
}
I've tried also to use @Component
instead of @Configuration
as it was mentioned here: Spring not using mongo custom converters
Other solutions I tried out: Naming the bean conversionServiceFactoryBean
instead of conversionService
. Or calling bean.afterPropertiesSet()
and retuning a ConversionService
using bean.getObject()
...
I've also tried to extend from WebMvcConfigurerAdapter
, overriding addFormatters
and add my converter there using addConverter
...
As mentioned here: How to register custom converters in spring boot? I've also tried to register the converter as a @Bean
directly.
It does not matter what I tried out, the UUIDConverter
will not be applied.
What is the correct solution do something like that in spring-boot?
Can anyone help here? What I'm doing wrong?
I only know about this issue because I've done the same myself with another class and spent hours debugging...
The UUIDConverter
is a bean already a registered by Spring itself. Choose literally any other name and you should see it appear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With