我是Spring Boot的新手.在我的控制器中,我使用UUIDs作为@PathVariable.默认情况下,弹簧MethodArgumentTypeMismatchException在传递无效时返回UUID.
当客户端传递无效时,UUID我想抛出一个自定义InvalidUUIDException,以便我能够使用此异常返回自定义的ErrorDto.
为了实现我正在尝试注册一个自定义UUIDConverter(实现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);
}
}
Run Code Online (Sandbox Code Playgroud)
要注册此组件,我将此Converter添加到弹簧ConversionService.使用ConversionServiceFactoryBean.
@Configuration
public class ConversionServiceConfiguration
{
@Bean
public ConversionServiceFactoryBean conversionService()
{
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(getConverters());
return bean;
}
private Set<Converter> …Run Code Online (Sandbox Code Playgroud)