Search code examples
c#.netpostgresqlnpgsql

C# Catch value of duplicate key from NpgSqlException


I know that when Postgres raises a duplicate key exception, it usually gives the value of the duplicate element in the detail of the exception itself.

    ERROR:  duplicate key value violates unique constraint "name_of_pkey"
    DETAIL:  Key (field_name)=(value) already exists.

From C#, how can i get that value from a NpgSqlException (NpgSql 3.1.7.0) now that the field Details has been removed from the exception class?


Solution

  • As mentioned in the 3.1 migration notes, in Npgsql 3.1 PostgreSQL errors are thrown as PostgresException, which extends NpgsqlException. NpgsqlExceptin is thrown for various client-side errors (e.g. networking).

    You'll find the Detail property on PostgresException.