2016-08-10 36 views
2

我想从insert语句或其他语句中捕获任何错误(即:外键错误)。我如何使用use Doctrine\DBAL\Exception来达到目的?使用Doctrine DBAL Exception捕获数据库错误

我有这样的,当我做了insert

  $db->beginTransaction(); 
      try { 
       $db->insert('bbc5.produccionpry',$datos); 
       $datos['propryid'] = $db->lastInsertId(); 
       $db->commit(); 
       // $db = null; 
       $resp[] = $datos; 
      } catch (Exception $e) { 
       $error = array_merge($error, array('error' => $e->errorInfo())); 
       $db->rollback(); 
       throw $e; 
      } 

但是,这并不妨碍concrete5到return网站讲述的错误,所以,我不想显示该网站,我要赶在array()错误,以便通过我不使用一个页面控制器echo json_encode($error)

返回它,我用它来管理从我的JavaScript应用程序调用REST风格与此代码:

return fetch(`/scamp/index.php/batchprodpry/${maq}`, { 
    method: 'POST', 
    credentials: 'same-origin', 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify(this.state.a) 
}) 

我使用ReactJS

谢谢

回答

2

不要抛出异常。

不是抛出异常,而是从DBALException $e对象中获取异常消息$e->getMessage()并将其编码为JSON字符串。 重要提示:echo之后加上exit;以确保不再执行代码。

use Doctrine\DBAL\DBALException; 

try { 
    $db->insert('bbc5.produccionpry',$datos); 
    $datos['propryid'] = $db->lastInsertId(); 
    $db->commit(); 
    $resp[] = $datos; 
} 
catch(DBALException $e){ 
    $db->rollback(); 
    echo \Core::make('helper/json')->encode($e->getMessage()); 
    exit; 
} 

如果此代码是一个页面控制器内,你可以这样做:

try { 
    $db->insert('bbc5.produccionpry',$datos); 
    $datos['propryid'] = $db->lastInsertId(); 
    $db->commit(); 
    $resp[] = $datos; 
} 
catch(DBALException $e){ 
    $this->error->add($e->getMessage()); 
} 

if($this->error->has()) { 
    // All variables that have been set in the view() method will be set again. 
    // That is why we call the view method again 
    $this->view(); 
    return; 
} 

而且concrete5将显示相应的错误信息的服务。

或者你也可以保存$e->getMesssage()在会话,并调用它的视图中:

$session = \Core::make('session'); 
// ... 
catch(Exception $e){ 
    $session->set('error', $e->getMessage()); 
} 

并在视图:

// html 
<?php 
$session = \Core::make('session'); 
if($session->has('error')) { 
    $m = $session->get('error'); 
    ?> 
    <div id="session_error" class="alert alert-danger"> 
     <a href="#" class="close">&times;</a> 

     <div id="session_error_msg"> 
      <?php print $m ?> 
     </div> 
    </div> 
<?php 
} 
$session->remove('error'); 
?> 
//html 
+0

你好,我还没有找到一个解决方案。我会尝试你的。谢谢 –

+0

你好,它没有工作。我一直返回错误网站,我只想从Mysql –

+0

的异常消息我得到我的数据库连接:'$ db = \ Database :: connection();' –

3

既然你在catch块有throw $e你抛出此异常进一步,这意味着它是(可能)由全球异常监听处理。一旦你抛出异常,你立即退出你的代码,所以你的解决方案只是删除throw $e行,你应该很好

+0

您好,我做到了,它仍然是。谢谢 –

+0

发表你的其他代码(catch块后是什么) –

+0

我有:** echo json_encode()** –