PHP中怎么捕獲異常并處理

本篇文章給大家分享的是有關(guān)PHP中怎么捕獲異常并處理,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比新榮網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式新榮網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋新榮地區(qū)。費(fèi)用合理售后完善,10余年實(shí)體公司更值得信賴。

<?php

header("Content-type:text/html;charset=utf-8");

try

{

    //業(yè)務(wù)處理 錯(cuò)誤時(shí)拋出異常。

    $age = 130;

    if ($age > 120) {

        throw new Exception('年齡不能大于120歲。', 1001);

    }

} catch (Exception $e) {

    $err = [

        'code' => $e->getCode(),

        'msg'  => $e->getMessage(),

        'file'    => $e->getFile(),

        'line'   => $e->getLine()

    ];

    echo json_encode($err);

}

輸出:{"code":1001,"msg":"\u5e74\u9f84\u4e0d\u80fd\u5927\u4e8e120\u5c81\u3002","file":"\/data\/mi\/demo.php","line":11}

自定義異常處理

<?php

header("Content-type:text/html;charset=utf-8");

class proException extends Exception

{

    //根據(jù)業(yè)務(wù)需求,自定義方法

    /**

     * 獲取錯(cuò)誤信息

     * @param int $type 類型 1=json 2=數(shù)組

     * @return array

     */

    public function getErrorInfo($type = 2)

    {

        $err = [

            'code' => $this->getCode(),

            'msg'  => $this->getMessage(),

            'file'    => $this->getFile(),

            'line'   => $this->getLine()

        ];

        if ($type == 1) {

            return json_encode($err);

        }

        return $err;

    }

}

try

{

    //業(yè)務(wù)處理 錯(cuò)誤時(shí)拋出異常。

    $age = 130;

    if ($age > 120) {

        throw new proException('年齡不能大于120歲。', 1001);

    }

} catch (proException $e) {

    $info = $e->getErrorInfo();

    var_dump($info);

}

輸出:array(4) { ["code"]=> int(1001) ["msg"]=> string(27) "年齡不能大于120歲。" ["file"]=> string(17) "/data/mi/demo.php" ["line"]=> int(53) }

捕捉多個(gè)異常

<?php

header("Content-type:text/html;charset=utf-8");

class proException extends Exception

{

    //根據(jù)業(yè)務(wù)需求,自定義錯(cuò)誤方法

    /**

     * 獲取錯(cuò)誤信息

     * @param int $type 類型 1=json 2=數(shù)組

     * @return array

     */

    public function getErrorInfo($type = 2)

    {

        $err = [

            'code' => $this->getCode(),

            'msg'  => $this->getMessage(),

            'file'    => $this->getFile(),

            'line'   => $this->getLine()

        ];

        if ($type == 1) {

            return json_encode($err);

        }

        return $err;

    }

}

try

{

    if ($_GET['age'] > 100) {

        throw new proException('自定義的異常處理', 1002);

    } else {

        throw new Exception('系統(tǒng)的異常處理', 1002);

    }

} catch (proException $e) {

    $info =  $e->getErrorInfo();

    var_dump($info);

} catch (Exception $e) {

    echo $e->getMessage();

}

?age=110 輸出:array(4) { ["code"]=> int(1002) ["msg"]=> string(24) "自定義的異常處理" ["file"]=> string(17) "/data/mi/demo.php" ["line"]=> int(64) }

?age=20 輸出:系統(tǒng)的異常處理。

日志記錄

//禁止錯(cuò)誤輸出

error_reporting(0);

//設(shè)置錯(cuò)誤處理器

set_error_handler('errorHandler');

//在腳本結(jié)束時(shí)運(yùn)行的函數(shù)

register_shutdown_function('fatalErrorHandler');

/**

 * 錯(cuò)誤處理

 * @param int    $err_no      錯(cuò)誤代碼

 * @param string $err_msg  錯(cuò)誤信息

 * @param string $err_file    錯(cuò)誤文件

 * @param int    $err_line     錯(cuò)誤行號(hào)

 * @return string

 */

function errorHandler($err_no = 0, $err_msg = '', $err_file = '', $err_line = 0)

{

    $log = [

        '['.date('Y-m-d h-i-s').']',

        '|',

        $err_no,

        '|',

        $err_msg,

        '|',

        $err_file,

        '|',

        $err_line

    ];

    $log_path = '/data/mi/test.txt';

    error_log(implode(' ',$log)."\r\n",3, $log_path);

    //echo implode(' ',$log)."<br>";

}

/**

 * 捕捉致命錯(cuò)誤

 * @return string

 */

function fatalErrorHandler() {

    $e = error_get_last();

    switch ($e['type']) {

        case 1:

            errorHandler($e['type'], $e['message'], $e['file'], $e['line']);

            break;

    }

}

class DemoClass_1

{

    public function index()

    {

        //這里發(fā)生一個(gè)警告錯(cuò)誤,出發(fā)errorHandler

        echo $undefinedVarible;

    }

}

$demo_1 = new DemoClass_1();

//這里發(fā)生一個(gè)警告錯(cuò)誤,被errorHandler 捕獲

$demo_1->index();

//發(fā)生致命錯(cuò)誤,腳本停止運(yùn)行觸發(fā) fatalErrorHandler

$demo_2 = new DemoClass_2();

$demo_2->index();

打開echo后 輸出:

[2016-08-07 09-01-34] | 8 | Undefined variable: undefinedVarible | /data/mi/demo.php | 126

[2016-08-07 09-01-34] | 1 | Class 'DemoClass_2' not found | /data/mi/demo.php | 134

備注:

1. register_shutdown_function 也可以用于API調(diào)試中,記錄每次請求值和返回值,方便調(diào)試。

2. 利用 “|” 分割的好處是,便于利用 awk 對日志進(jìn)行分割處理。

以上就是PHP中怎么捕獲異常并處理,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)站欄目:PHP中怎么捕獲異常并處理
文章源于:http://www.muchs.cn/article24/jdocce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站網(wǎng)站設(shè)計(jì)公司、品牌網(wǎng)站建設(shè)、定制網(wǎng)站、軟件開發(fā)、品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)