This is my DAO object that takes the Cypher query as a string, and returns a JSON representation of the graph it returns.
Because it's using a Spring JdbcTemplate
to access the database, the jdbc query will return any errors wrapped in a DataAccessException
.
What I'm wanting to do here, is detect whether the error being thrown is due to an invalid query (in which case I want to return a message to the user saying so), or for now, any other error, in which case I'll file it as 'An unexpected error occurred'.
public String runQuery(String q) throws JsonGenerationException, JsonMappingException, UncategorizedSQLException, DataAccessException
{
Graph g = null;
try {
g = jdbcTemplate.query(q, new Neo4jGraphResultSetExtractor());
} catch (DataAccessException e) {
if (e instanceof UncategorizedSQLException)
{
//Invalid cypher query
throw (UncategorizedSQLException)e;
}
else throw e;
}
json = g.toJson(); //throws JsonGenerationException, JsonMappingException
return json;
}
When I call the DAO from my Business Layer:
public String submitCypherQuery(String query) {
try {
return neoConn.runQuery(query);
} catch (ClassNotFoundException e) {
return handleUnexpectedError(e);
} catch (JsonGenerationException e) {
return handleUnexpectedError(e);
} catch (JsonMappingException e) {
return handleUnexpectedError(e);
} catch (IOException e) {
return handleUnexpectedError(e);
}
catch (UncategorizedSQLException e)
{
return new ErrorMessage(errorInvalidQuery).toJson();
}
catch (DataAccessException e)
{
return handleUnexpectedError(e);
}
}
Is this an OK way of doing this?
One question I have is that both UncategorizedSQLException
, DataAccessException
are unchecked exceptions, meaning that even though the DAO has declared them as being thrown - the compiler is fine with calling these methods without being surrounded in a try/catch.
This isn't especially useful - this is the exact case I want to force the developers to handle!