如何捕获hex2bin()警告

Abe*_*ela 2 php

今天遇到这个,不知道如何解决它.

我想捕获hex2bin()E_WARNING发出的级别错误.

我以为我可以使用try()catch()异常方法,但它不起作用.

try {
    $foo = hex2bin($bar);
}
catch (Exception $e) {
    die('Custom message');
}
Run Code Online (Sandbox Code Playgroud)

发布的标准E_WARNING当然是:

警告:hex2bin():输入字符串必须是十六进制字符串

在这种特殊情况下我也不会想使用标准方法来禁用错误,如:

error_reporting(-1);
error_reporting(E_ALL);
ini_set("display_errors", 1);
Run Code Online (Sandbox Code Playgroud)

我也不想使用@hex2bin方法来抑制错误.

我实际上想要显示一个自定义错误,但我似乎无法在hex2bin抛出错误时找到一种方法来捕获.

小智 6

您可以检查输入值以在将其传递给hex2bin方法之前验证它是否为十六进制.

if (ctype_xdigit($bar) && strlen($bar) % 2 == 0) {
    $foo = hex2bin($bar);
} else {
    //display error here
}
Run Code Online (Sandbox Code Playgroud)