'C# Npgsql connection checker Exception Throw System.NullReferenceException 'Object reference not set to an instance of an object.'
My code try to check is the PostgreSQL server running and accessible by given credentials for given database. Use the Npgsql NuGet. If all the data, also IP, Port, User, Pass and Database are correct, the code returns true.
Here is a code:
public Boolean InsertInToPGSQL()
{
var pg_con_string = "Server=" + sqlinsertserver + ";" + "Port=" + sqlinsertport + ";" + "Database=" + sqlinsertdatabase + ";" + "User ID=" + sqlinsertusername + ";" + "Password=" + sqlinsertpassword + ";";
var pg_connetion = new NpgsqlConnection(pg_con_string);
try
{
if (pg_connetion != null)
{
pg_connetion.Open();
pg_connetion.Close();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
The problem is if i write an IP address where is no server running, or bad port, or wrong user/pass, database, i receive always on:
pg_connetion.Open();
An error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
The problem is that a catch (Exception) don't catch this error and returns simple false.
I don't need to deal with type of errors, like wrong credential or IP / port, just need to have true on successful connection to the PostgreSQL server and false for any other case.
How to deal with this error?
Solution 1:[1]
To get exception details you need to do catch(Exception ex) and within catch block you can do ex.InnerException or ex.Message to find the exception details. In your case, the connection object is null because of incorrect parameters. I would do a null check on connection object before connection.open() which would avoid object ref not set to instance. Hope that should suffice your need. Change your code to following and send me the ex.Message and ex.InnerException values.
public static class Application
{
public static void Main()
{
if (InsertInToPGSQL())
Console.WriteLine("Connection successful");
else
Console.WriteLine("Connection failed");
Console.ReadLine();
}
public static Boolean InsertInToPGSQL()
{
var pg_con_string = "";
var pg_connetion = new NpgsqlConnection(pg_con_string);
try
{
if (pg_connetion != null)
{
pg_connetion.Open();
pg_connetion.Close();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
}
``
Solution 2:[2]
Maybe late, but for those like me who felt on this thread it can be usefull.
I faced the same issue until i update the NpSql nuget package. I was on 4.0.3, and update to 4.1.10. Finaly it fixed the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Yaegaki2 |