javacassandradropwizarddatastax-java-driver

java.lang.NumberFormatException when trying to fetch a line in a Cassandra table


I use the Datastax driver to fetch a line in a Cassandra table :

 MappingManager manager = new MappingManager(session);
 Mapper<CassandraEntity> mapper = manager.mapper(CassandraEntity.class);
 UUID id = UUID.fromString(uuid);    
 CassandraEntity cassandraEntity = mapper.get(id);

When the uuid exists in the table then everything works fine. But when the uuid does not exist I have this error :

ERROR [2017-01-27 14:27:24,030] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 48a3bf442525acf8
! java.lang.NumberFormatException: For input string: "68c34e83db3o"
! at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.7.0_75]
! at java.lang.Long.parseLong(Long.java:441) ~[na:1.7.0_75]
! at java.lang.Long.valueOf(Long.java:513) ~[na:1.7.0_75]
! at java.lang.Long.decode(Long.java:665) ~[na:1.7.0_75]
! at java.util.UUID.fromString(UUID.java:206) ~[na:1.7.0_75]

How can I nicely manage this error ?


Solution

  • c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3o is not a valid UUID. The sixteen octets of a UUID are represented as 32 lowercase hexadecimal (base 16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). So :

    But c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3g is not a valid UUID nor c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3o

    To quickly check if a UUID is valid you can use this Fiddle : https://jsfiddle.net/mshaffer/6e2Ljh97

    As Andy Tolbert said, when the UUID is not valid then the UUID.fromString method throws an IllegalArgumentException. To handle this exception, use the solution given at How to judge a string is UUID type? :

    try{
        UUID uuid = UUID.fromString(someUUID);
        //do something
    } catch (IllegalArgumentException exception){
       //handle the case where string is not valid UUID 
    }