如果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();
}
}
正如您所看到的,我正在使用最终构建来回滚事务。这是正确的做法吗?
答案 0 :(得分:1)
您可以捕获一个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())
}
}