搜尋
首頁頭條看看PHP 7.3新版的JSON錯誤處理

背景

在目前穩定的PHP V7.2中,如果你想確定JSON是無效的,你必須使用json_last_error()功能驗證:

>>> json_decode("{");
=> null
>>> json_last_error();
=> 4
>>> json_last_error() === JSON_ERROR_NONE
=> false
>>> json_last_error_msg()
=> "Syntax error"

例如,在Larave這裡檢查以確保調用JSON編碼不會導致錯誤:

// Once we get the encrypted value we'll go ahead and base64_encode the input
// vector and create the MAC for the encrypted value so we can then verify
// its authenticity. Then, we'll JSON the data into the "payload" array.
$json = json_encode(compact('iv', 'value', 'mac'));
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new EncryptException('Could not encrypt the data.');
}
return base64_encode($json);

我們至少可以確定如果JSON編碼/解碼有錯誤,但相比有點笨重,拋出一個異常,放出錯誤代碼和錯誤訊息。

雖然你已經選擇了,捕捉和處理JSON,另外讓我們看看新的版本,我們可以用一個很好的方式!

在PHP 7.3錯誤標誌的拋出

隨著新的選項標誌JSON_THROW_ON_ERROR有可能改寫這一塊的程式碼使用try/catch。

也許類似下面的:

use JsonException;
try {
    $json = json_encode(compact('iv', 'value', 'mac'), JSON_THROW_ON_ERROR);
    return base64_encode($json);
} catch (JsonException $e) {
    throw new EncryptException('Could not encrypt the data.', 0, $e);
}

我認為這一新風格是特別有用的用戶代碼,當你收到一些JSON數據而不是搜尋json_last_error()和匹配的選項,JSON編碼和解碼可以利用錯誤處理程序。

這個json_decode()功能有幾個參數,並且會看起來像PHP 7.3以下如果你想利用錯誤處理:

use JsonException;
try {
    return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    // Handle the JSON Exception
}
// Or even just let it bubble up...
/** 
 * Decode a JSON string into an array
 *
 * @return array
 * @throws JsonException
 */
function decode($jsonString) {
    return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR);
}

得到的錯誤代碼和錯誤訊息

以前你取得JSON錯誤代碼和訊息使用以下功能:

// Error code
json_last_error();
// Human-friendly message
json_last_error_msg();

如果你使用新的JSON_THROW_ON_ERROR,這裡是你如何使用程式碼和取得訊息:

try {
    return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    $e->getMessage(); // like json_last_error_msg()
    $e->getCode(); // like json_last_error()
}
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具