Php 仅当发生异常但存在多个catch子句时才执行语句

Php 仅当发生异常但存在多个catch子句时才执行语句,php,Php,如果try块中的任何内容失败,我需要回滚事务并向客户端发送正确的响应,所以我这样做: try { $wf = $this->createWordForm($requestParams); $wfl = $this->createWordFormLink($requestParams, $wf); $wordList = $this->bindWordFormOrLinkToTextWord($requestParams, $wf, $wfl);

如果try块中的任何内容失败,我需要回滚事务并向客户端发送正确的响应,所以我这样做:

try {
    $wf = $this->createWordForm($requestParams);
    $wfl = $this->createWordFormLink($requestParams, $wf);
    $wordList = $this->bindWordFormOrLinkToTextWord($requestParams, $wf, $wfl);
    $db->commit();
} catch (Kohana_ORM_Validation_Exception $e) {
    $exceptionHasOccured = TRUE;
    return JsonResponse::ValidationFail($this->response, $e->errors());
} catch (Exception $e) {
    $exceptionHasOccured = TRUE;
    return JsonResponse::Error($this->response, $e->getMessage());
} finally {
    if ($exceptionHasOccured) {
        $db->rollback();
    }
}

如您所见,我使用finally构造回滚事务。这是正确的方法吗?

您可以在一个catch块中捕获所有异常,只要您没有专门将异常类型用于任何目的

try {
    $wf = $this->createWordForm($requestParams);
    $wfl = $this->createWordFormLink($requestParams, $wf);
    $wordList = $this->bindWordFormOrLinkToTextWord($requestParams, $wf, $wfl);
    $db->commit();
} catch (Exception $e) {
    $db->rollback();
    if($e instanceof Kohana_ORM_Validation_Exception ) { 
       return JsonResponse::ValidationFail($this->response, $e->errors());
    } else {
       return JsonResponse::Error($this->response, $e->getMessage())
    }
} 

我只是在两个
catch
块中复制
$db->rollback()
行。留着simple@Phil谢谢,这就是我最初做的:)我根据异常类型返回不同类型的错误,并为此添加了修复程序@马克西姆有一双好眼睛。用一种可能的方法再次更新,仍然只有一次回滚。是的,我也想到了,谢谢。我投了赞成票。然而,我想我还是会坚持使用两个回滚语句的选项。