我正在像这样连接到本地postgresql实例:
try
{
using (var connection = new NpgsqlConnection(connectionString))
{
using (var command = new NpgsqlCommand("loadProjects", connection))
{
command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (NpgsqlDataReader dataReader = command.ExecuteReader())
{
...
}
}
}
}
catch (NpgsqlException ex)
{
...
}
然后出于测试目的,我从任务管理器中停止数据库服务器=>服务,当我尝试连接时当然会出现异常:“无法建立连接,因为目标计算机主动拒绝了它“但有趣的是,此异常未被catch块捕获,而只是使我的程序在line connection.Open()崩溃。任何人都可以解释,为什么会这样?
我建议您更改
catch (NpgsqlException ex)
{
...
}
到
catch (Exception ex)
{
...
}
并查看异常的实际类型
它可以是“ PostgresException” https://www.npgsql.org/doc/api/Npgsql.PostgresException.html
尝试此操作。您的try-catch块不在使用NpsqlConnection的范围内。
using (var connection = new NpgsqlConnection (connectionString)) {
using (var command = new NpgsqlCommand ("loadProjects", connection)) {
command.CommandType = CommandType.StoredProcedure;
try {
connection.Open ();
using (NpgsqlDataReader dataReader = command.ExecuteReader ()) {
...
}
} catch (NpgsqlException ex) {
...
}
}
}