如何在YII2中处理/捕获数据库触发器中的错误

时间:2015-07-02 05:22:21

标签: database error-handling triggers yii2

这是我的触发器

CREATE OR REPLACE TRIGGER trg_cek_pengurus
BEFORE INSERT ON tbl_pengurus
FOR EACH ROW
DECLARE
    v_cek NUMBER(2);
BEGIN

IF :NEW.jabatan = 1 OR :NEW.jabatan = 2 THEN

    select count(id)
    into v_cek
    from tbl_pengurus
    where idkoperasi = :NEW.idkoperasi and jabatan = :NEW.jabatan;

    IF v_cek > 0 THEN
        RAISE_APPLICATION_ERROR (-20000, 'kepengurusan sudah ada');
    END IF;

END IF;
END;
/

nah ..,如果触发器有一个返回值是好的,:v但它没有:v 所以我设置了RAISE_APPLICATION_ERROR

这是我的控制器

public function actionTambahPengurus()
{
    $model = new Pengurus();
     if ($model->load(Yii::$app->request->post())){
        $model->IDKOPERASI = Yii::$app->user->identity->ID;
        if($model->save())
            return $this->redirect('kepengurusan');
     }

    return $this->render('tambah-pengurus',[
        'model' => $model,
    ]);
}

然后我收到错误

SQLSTATE[HY000]: General error: 20000 OCIStmtExecute: ORA-20000: kepengurusan sudah ada
ORA-06512: at "DB_KOPERASI.TRG_CEK_PENGURUS", line 13
ORA-04088: error during execution of trigger 'DB_KOPERASI.TRG_CEK_PENGURUS'
(ext\pdo_oci\oci_statement.c:148)
The SQL being executed was: INSERT INTO "TBL_PENGURUS" ("NIK", "NAMA", "JABATAN", "EMAIL", "TGL_LAHIR", "ALAMAT", "TELEPON", "IDKOPERASI") VALUES ('2110131041', 'Rahmat Heru Kurniawan', 1, 'rahmatheruka2@gmail.com2', '3 July, 2015', 'sidoarjo', '0987654321', 8) RETURNING "ID" INTO :qp8

这很好,因为这告诉我触发器正在工作 但这当然对我的网站不好。 所以我想处理这个问题,我尝试了谷歌的各种方式,但没有任何作用。 请..有谁可以帮助我?

1 个答案:

答案 0 :(得分:9)

据我记忆,任何与数据库相关的错误都会抛出yii\db\Exception。您可以使用标准try / catch块来处理:

try {
    ...
} catch (\yii\db\Exception $e) {
    ...
}