ERROR_MESSAGE Function - SQL Server to PostgreSQL Migration

In SQL Server, the ERROR_MESSAGE function returns the error text of an exception and can only be used within a CATCH block.

In PostgreSQL, you can use the SQLERRM variable, which contains the error message of the most recent exception.

SQL Server:

  CREATE TABLE t1 (c1 INT NOT NULL);
 
  BEGIN TRY
     -- Try to insert NULL into non-nullable column
     INSERT INTO t1 VALUES (NULL); 
  END TRY  
  BEGIN CATCH
    PRINT 'Error message: ' + ERROR_MESSAGE()
  END CATCH 
  /* Error message:
      Cannot insert the value NULL into column 'c1', table 'test.dbo.t1'; column does not allow nulls. INSERT fails. */

PostgreSQL:

  CREATE TABLE t1 (c1 INT NOT NULL);
 
  DO $$
  BEGIN
     -- Try to insert NULL into non-nullable column
     INSERT INTO t1 VALUES (NULL); 
  EXCEPTION WHEN OTHERS THEN
    RAISE NOTICE '%','Error message: ' || SQLERRM;
  END; $$;
  /* NOTICE:  Error message: null value in column "c1" of relation "t1" violates not-null constraint */

For more information, see SQL Server to PostgreSQL Migration.