Lớp ErrorException
Lớp ErrorException kế thừa từ lớp cơ sở Exception và được sử dụng
để chuyển đổi các lỗi PHP thành ngoại lệ. Nó bổ sung thông tin về mức độ nghiêm trọng (severity) của lỗi
vào chức năng tiêu chuẩn của ngoại lệ. Lớp này đặc biệt hữu ích
khi sử dụng với hàm set_error_handler.
Cú pháp
new ErrorException(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
string $filename = __FILE__,
int $lineno = __LINE__,
Throwable $previous = null
);
Ví dụ
Tạo và xử lý ErrorException:
<?php
try {
throw new ErrorException('Critical error', 0, E_ERROR);
} catch (ErrorException $e) {
echo 'Error: ' . $e->getMessage();
echo ' Severity: ' . $e->getSeverity();
}
?>
Kết quả thực thi mã:
'Error: Critical error Severity: 1'
Ví dụ
Chuyển đổi các lỗi tiêu chuẩn của PHP thành ngoại lệ:
<?php
function errorHandler($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler('errorHandler');
try {
strpos(); // Sai số lượng tham số
} catch (ErrorException $e) {
echo 'Caught exception: ' . $e->getMessage();
echo ' in ' . $e->getFile();
echo ' on line ' . $e->getLine();
}
?>
Kết quả thực thi mã (ví dụ):
'Caught exception: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'
Ví dụ
Lấy thông tin về mức độ nghiêm trọng của lỗi:
<?php
try {
throw new ErrorException('Warning message', 0, E_WARNING);
} catch (ErrorException $e) {
echo 'Severity level: ' . $e->getSeverity();
echo ' Is warning: ' . ($e->getSeverity() === E_WARNING ? 'yes' : 'no');
}
?>
Kết quả thực thi mã:
'Severity level: 2 Is warning: yes'
Xem thêm
-
lớp
Exception,
lớp cơ sở cho tất cả các ngoại lệ trong PHP -
hàm
set_error_handler,
thiết lập một bộ xử lý lỗi tùy chỉnh