2016-11-11 102 views
3

我希望能夠返回一個異常,並且php會這樣做。但是,PHP也會返回特定異常的上下文,我不太喜歡前端用戶看到。有什麼方法可以顯示錯誤部分而不是異常的上下文部分?如何獲得pg_last_error的特定部分

 $query3 = "INSERT INTO sis.enrolledsubject (offeringno, regno) 
     VALUES ('$offering','$regno')"; 
     if (pg_query($query3)) { 
      echo "New subject added successfully!"; 
     } else { 
      echo pg_last_error($dbconn); 
     } 

的錯誤是這樣的:

ERROR: //My exception string here// 
CONTEXT: PL/pgSQL function resolveconflict() line 44 at RAISE 

我只是想顯示錯誤,而不是錯誤的情況下。我試過類似pg_result_error_field但無濟於事。我希望有人能幫助我。謝謝!

+1

它說明了什麼錯誤? –

+0

類似這樣:'錯誤://我的異常字符串在這裏// 上下文:PL/pgSQL函數resolveconflict()第44行在RAISE' 我想只顯示錯誤部分而不顯示上下文部分 –

+0

請參見: http://stackoverflow.com/questions/12349230/catching-errors-from-postgresql-to-php –

回答

0

這裏有一個SSCCE

<?php 

function error_exit($msg) 
{ 
    fwrite(STDERR, "ERROR: $msg\n"); 
    exit(1); 
} 

$db = pg_connect(""); 
pg_query("create temporary table test(id int primary key)") 
    or error_exit(pg_last_error($db)); 

foreach (array_slice($argv, 1) as $arg) { 
    pg_send_query_params($db, "insert into test(id) values ($1)", [$arg]) 
    or error_exit(pg_last_error($db)); 
    $result = pg_get_result($db) 
    or error_exit(pg_last_error($db)); 
    if (pg_result_status($result) == PGSQL_FATAL_ERROR) 
    error_exit(pg_result_error_field($result, PGSQL_DIAG_MESSAGE_PRIMARY)); 
} 

?> 

試試:

$ php test.php 1 2 2 
ERROR: duplicate key value violates unique constraint "test_pkey" 

$ php test.php 1 2 a 
ERROR: invalid input syntax for integer: "a"