Neo4j .NET驱动程序错误处理

时间:2016-10-28 08:19:47

标签: .net neo4j cypher

我几天前开始使用Neo4j数据库,最后我遇到了一个我不熟悉.NET驱动程序的问题。我有这样的代码:

using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j")))
using (var session = driver.Session())
{
    foreach(...)
        {
        // Build cypher query
        string cypher_query = "...";

        try
        {
            session.Run(cypher_query).Consume();
        }
        catch (Exception e)
        {
            Console.WriteLine("Failed running query : " + cypher_query + "\r\n" + e.Message);
        }
    }
}

我需要在foreach循环中运行大量的密码查询(所有都是MERGE查询)。我的问题是在获得第一个异常后所有查询都失败了。

当我查看我在控制台中显示的内容时,cypher_query变量包含正确的内容并在每次迭代时更改,但异常消息始终保持不变。

当我调试时,我感觉查询已正确执行但我们仍然执行了catch子句。

知道会发生什么事吗?

1 个答案:

答案 0 :(得分:1)

我意识到这是陈旧的,但原因是该异常导致会话进入无效状态。

此代码执行以显示问题,首先是包装器方法:

public static void ExecuteCypher(IDriver driver, ISession session, string cypher, bool createNewSessionOnException = true)
{
    try
    {
        //Attempt to run the cypher...
        session.Run(cypher).Consume();
    }
    catch (Exception e)
    {
        //Write out error caught
        Debug.WriteLine("Caught Exception: {0}", e.ToString());

        //If we should create a new session 
        if (createNewSessionOnException)
        {
            //first clear up the old one
            session.Dispose();

            //Create new one
            Console.WriteLine("New Session");
            session = driver.Session();
        }
    }
}

你称之为:

using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j")))
{
    var session = driver.Session();
    ExecuteCypher(driver, session, "Broken Cypher");
    ExecuteCypher(driver, session, "Match (x) RETURN count(x)");
    session.Dispose();
}    

哪个工作,但是如果您更改它以便它不会创建新会话,您将获得例外:

using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j")))
{
    var session = driver.Session();
    ExecuteCypher(driver, session, "Broken Cypher", false); //<-- here
    ExecuteCypher(driver, session, "Match (x) RETURN count(x)");
    session.Dispose();
}