如何在外部dll中捕获异常

本文关键字:捕获异常 dll 外部 | 更新日期: 2023-09-27 18:08:08

我想捕获当我尝试使用Neo4jClient.dll连接到我的neo4j数据库时发生的异常。如果数据库离线,我得到以下错误:"类型为'System '的异常。AggregateException'在mscorlib.dll中发生,但未在用户代码中处理。"我的catch-block从未到达。

这是我的代码:

class Neo4JConnector
{
    private static GraphClient client = null;
    public Neo4JConnector(IniConfigSource configSource)
    {
        if (client == null)
        {
            client = new GraphClient(new Uri(configSource.Configs["Configuration"].Get("Neo4jUrl")));
            try
            {
                client.Connect();
            }
            catch (Exception ex) 
            {
                Console.WriteLine("Cannot connect"); // never reached :(
            }

然后我尝试使用"extern"修饰符与以下代码:

class Neo4JConnector
{
    private static GraphClient client = null;
    [DllImport("Neo4jClient.dll", EntryPoint="Connect")]
    static extern void Connect();
    public Neo4JConnector(IniConfigSource configSource)
    {
        if (client == null)
        {
            client = new GraphClient(new Uri(configSource.Configs["Configuration"].Get("Neo4jUrl")));
            try
            {
                Connect();
            }
            catch (Exception ex) 
            {
                Console.WriteLine("Cannot connect");
            }
        }

但是我得到的只是一个Exception,它说"[System.]"无法在DLL 'Neo4jClient.dll'中找到名为'Connect'的入口点。": "} "

这是Neo4jClient.dll中签名的样子

public virtual void Connect();

我的代码有什么问题?是否有更好的方法来捕获外部异常?请帮忙:(

如何在外部dll中捕获异常

解决方案是在异常设置菜单中取消勾选"当抛出此异常类型时中断",当异常在外部库中抛出时。之后,我的catch-block达到了。不需要使用[DllImport]

根据GitHub的repo, "Neo4jClient.dll"是一个。net程序集。你应该从你的项目中添加引用并使用这些方法。

下面是一个例子:

using Neo4jClient;
...
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();