Hướng dẫn php 8 catch fatal error - php 8 bắt lỗi nghiêm trọng

Giải pháp tốt đẹp được tìm thấy trong Zend Framework 2:

/**
 * ErrorHandler that can be used to catch internal PHP errors
 * and convert to an ErrorException instance.
 */
abstract class ErrorHandler
{
    /**
     * Active stack
     *
     * @var array
     */
    protected static $stack = array();

    /**
     * Check if this error handler is active
     *
     * @return bool
     */
    public static function started()
    {
        return (bool) static::getNestedLevel();
    }

    /**
     * Get the current nested level
     *
     * @return int
     */
    public static function getNestedLevel()
    {
        return count(static::$stack);
    }

    /**
     * Starting the error handler
     *
     * @param int $errorLevel
     */
    public static function start($errorLevel = \E_WARNING)
    {
        if (!static::$stack) {
            set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
        }

        static::$stack[] = null;
    }

    /**
     * Stopping the error handler
     *
     * @param  bool $throw Throw the ErrorException if any
     * @return null|ErrorException
     * @throws ErrorException If an error has been catched and $throw is true
     */
    public static function stop($throw = false)
    {
        $errorException = null;

        if (static::$stack) {
            $errorException = array_pop(static::$stack);

            if (!static::$stack) {
                restore_error_handler();
            }

            if ($errorException && $throw) {
                throw $errorException;
            }
        }

        return $errorException;
    }

    /**
     * Stop all active handler
     *
     * @return void
     */
    public static function clean()
    {
        if (static::$stack) {
            restore_error_handler();
        }

        static::$stack = array();
    }

    /**
     * Add an error to the stack
     *
     * @param int    $errno
     * @param string $errstr
     * @param string $errfile
     * @param int    $errline
     * @return void
     */
    public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
    {
        $stack = & static::$stack[count(static::$stack) - 1];
        $stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
    }
}

Lớp này cho phép bạn bắt đầu

interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
1 cụ thể đôi khi nếu bạn cần. Và sau đó bạn cũng có thể ngăn chặn người xử lý.

Sử dụng lớp này, ví dụ: như thế này:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;

Liên kết đến mã lớp đầy đủ: https://github.com/zendframework/zf2/blob/master/l Library/zend/stdlib/errorhandler.php
https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php

Một giải pháp tốt hơn có lẽ là một giải pháp từ Monolog:

Liên kết đến mã lớp đầy đủ: https://github.com/seldaek/monolog/blob/master/src/monolog
https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php

Nó cũng có thể xử lý Fatal_errors bằng hàm

interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
2. Theo lớp này, Fatal_error là một trong những điều sau đây.

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}

PHP là ngôn ngữ được sử dụng để xây dựng các trang web trên Internet trong hơn mười năm. Mặc dù, có rất nhiều người nghĩ rằng đã đến lúc chuyển sang một thứ khác, PHP là ngôn ngữ lập trình năng động, điều đó có nghĩa là nó có thể thích nghi với các nhu cầu hiện tại. Và nhóm php Core đã rất xuất sắc trong việc đưa ra các tính năng mới làm cho PHP trở thành một ngôn ngữ hấp dẫn trong thời gian này.

Tính linh hoạt trong ngôn ngữ PHP giúp dễ dàng xử lý những thứ như ngoại lệ trong mã, đó là các kịch bản thông thường có thể xảy ra. Chúng có thể được gây ra bởi một số đầu vào bất ngờ, lỗi hoặc một số vấn đề khác. Php 8 là phiên bản mới của ngôn ngữ này được phát hành vào ngày 26 tháng 11 năm 2020. Phiên bản mới đã được điều chỉnh để an toàn hơn và xử lý các ngoại lệ tốt hơn các phiên bản trước.

Các trường hợp ngoại lệ/lỗi tiềm năng được đặt trong một khối thử nếu gặp ngoại lệ, sẽ được ném để bắt hoặc cuối cùng chặn. PHP thường xử lý các ngoại lệ trong một khối bắt riêng cho từng loại ngoại lệ khác nhau.

Trong bài đăng này, bạn có thể có được kiến ​​thức về chính xác những gì là xử lý ngoại lệ và cách thức hoạt động của nó.

Dưới đây là các chủ đề sẽ được đề cập trong blog này:

  1. Khi nào, ở đâu và làm thế nào để sử dụng các ngoại lệ và lỗi trong PHP?
  2. Lớp lỗi
  3. Lớp ngoại lệ
  4. Ngoại lệ tùy chỉnh
  5. Nhiều ngoại lệ
  6. Trình xử lý ngoại lệ toàn cầu
  7. Bắt không bắt giữ

#1 khi nào, ở đâu và làm thế nào để sử dụng các ngoại lệ và lỗi trong PHP?

Php 7 đã giới thiệu giao diện có thể ném mới để hợp nhất ngoại lệ ngoại lệ và lỗi. Toàn bộ phân cấp ngoại lệ PHP như sau:Throwable interface to unite the exception branches Exception and Error. The entire PHP exception hierarchy is as follows:

interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception

Để bắt cả ngoại lệ và lỗi trong Php 8, hãy thêm một khối bắt để ngoại lệ sau khi bắt

interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
4 trước.

try 
{ 
    // Code that may throw an Exception or Error. 
} catch (Throwable $t) 
{ 
   // Executed only in PHP 7 and more
}

#2 Lớp lỗi

Lớp lỗi là lớp cơ sở cho tất cả các lỗi PHP nội bộ. Lỗi có thể bị bắt trong & nbsp; thử/bắt khối như đã giải thích ở trên. Rất ít lỗi sẽ ném một lớp lỗi cụ thể của lỗi như lỗi phân tích cú pháp, lỗi loại, v.v. is the base class for all internal PHP errors. Errors can be caught in  try/catch block as explained above. Few errors will throw a specific subclass of Error such as Parse Error, Type Error, and so on.

Dưới đây là danh sách các loại lỗi khác nhau (chúng tôi chỉ đề cập đến các loại phổ biến nhất):

  1. Lỗi phân tích cú pháp/cú pháp
  2. Loại lỗi
  3. Lỗi số học
  4. Lỗi xác nhận
  5. Lỗi giá trị

một. Lỗi phân tích cú pháp/cú pháp

Lỗi cú pháp/phân tích cú pháp trong mã trong khi biên dịch, lỗi phân tích cú pháp được ném. Nếu một mã chứa lỗi, trình phân tích cú pháp PHP không thể giải thích mã và nó ngừng hoạt động.syntax/parse error in the code while compilation, a Parse error is thrown. If a code contains an error, the PHP parser cannot interpret the code and it stops working.

Chúng ta hãy xem xét một ví dụ đơn giản để hiểu lỗi phân tích cú pháp.

Code:

Đầu ra:

syntax error, unexpected '=' in line 3

b. Loại lỗi

Khi sự không phù hợp kiểu dữ liệu xảy ra trong PHP trong khi thực hiện một thao tác, một lỗi loại được ném. Có ba kịch bản trong đó loại lỗi này được ném:Type error is thrown. There are three scenarios where this type of error is thrown:

  • Số lượng đối số không hợp lệ được truyền cho một hàm tích hợp.
  • Giá trị được trả về từ một hàm không khớp với loại trả về hàm được khai báo.
  • Loại đối số được truyền đến một hàm không khớp với loại tham số được khai báo.

Chúng ta hãy xem xét một ví dụ đơn giản để hiểu lỗi loại.

Code:

getMessage(), "\n";
}
?>

Đầu ra:

Argument 1 passed to add() must be of the type integer, string given.

b. Loại lỗi

Khi sự không phù hợp kiểu dữ liệu xảy ra trong PHP trong khi thực hiện một thao tác, một lỗi loại được ném. Có ba kịch bản trong đó loại lỗi này được ném:Arithmetic error is thrown.

Số lượng đối số không hợp lệ được truyền cho một hàm tích hợp.

getMessage();
}
?>

Đầu ra:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
0

b. Loại lỗi

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
1

Đầu ra:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
2

b. Loại lỗi

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
3

Output:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
4

Explanation:

Khi sự không phù hợp kiểu dữ liệu xảy ra trong PHP trong khi thực hiện một thao tác, một lỗi loại được ném. Có ba kịch bản trong đó loại lỗi này được ném:

interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
7. When any variable divided by zero with modulo operator returns
interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
8 and the variable divided by zero with the division operator also returns anyone the following-
interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
9

Số lượng đối số không hợp lệ được truyền cho một hàm tích hợp.

Giá trị được trả về từ một hàm không khớp với loại trả về hàm được khai báo.Assertion error is thrown. String description emits E_DEPRECATED message from PHP 7.2 version. The Assertion Error thrown by assert() will be sent to catch block only if assert.exception=on is enabled in php.ini.

Chúng ta hãy xem xét một ví dụ đơn giản để hiểu lỗi xác nhận.

Code:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
5

Output:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
6

e. Lỗi giá trị

Khi loại đối số là chính xác và giá trị của nó không chính xác, một lỗi giá trị được ném. Những loại lỗi này xảy ra khi:value error is thrown. These type of errors occurs when:

  • Vượt qua một giá trị âm khi hàm mong đợi một giá trị dương.
  • Truyền một chuỗi trống hoặc mảng khi hàm mong đợi một chuỗi/mảng không trống.

Chúng ta hãy xem xét một ví dụ đơn giản để hiểu lỗi giá trị.

Code:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
7

Output:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
8

Code:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;
9
class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
0

#3 lớp ngoại lệ

Lớp ngoại lệ xảy ra khi một điều kiện lỗi được chỉ định/đặc biệt thay đổi luồng thông thường của thực thi mã. occurs when a specified/exceptional error condition changes the normal flow of the code execution.

Xử lý ngoại lệ bao gồm năm thành phần tức là, hãy thử khối, ngoại lệ, ném, bắt khối và cuối cùng là khối.

Hãy xem xét một ví dụ đơn giản để hiểu các thành phần nêu trên

Code:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
1

Output:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
2

Explanation:

Ví dụ của chúng tôi là về việc thêm hai số và chúng tôi giả định rằng chúng tôi có thể nhận được giá trị không phải là đầu vào sẽ gây ra lỗi.

  • Chúng tôi đã tạo một hàm có tên bổ sung với ngoại lệ cho các giá trị không phải là số và nếu gặp ngoại lệ, sẽ ném nó với thông báo ngoại lệ.

  • Chúng tôi đã gọi hàm bổ sung bên trong một khối thử để lỗi giá trị không phải là số không ảnh hưởng/dừng toàn bộ thực thi. Tất cả các trường hợp ngoại lệ tiềm năng nên được đặt trong một khối thử.

  • Khối Catch sẽ nhận được bất kỳ trường hợp ngoại lệ nào được ném từ khối thử và thực thi mã bên trong khối. Trong trường hợp của chúng tôi sẽ in thông báo lỗi 'Ngoại lệ bị bắt: Num2 không phải là số'.

  • Khối cuối cùng sẽ được thực thi bất kể chúng tôi có nhận được ngoại lệ hay không.

#4 Ngoại lệ tùy chỉnh

Chúng tôi sử dụng ngoại lệ tùy chỉnh để làm rõ những gì đang bị bắt trong khối bắt và để hiểu ngoại lệ theo cách tốt hơn. Lớp ngoại lệ tùy chỉnh kế thừa các thuộc tính từ lớp ngoại lệ PHP, nơi bạn cũng có thể thêm các chức năng tùy chỉnh của mình. Để dễ dàng hiểu được các ngoại lệ, chúng tôi có thể sử dụng các ngoại lệ tùy chỉnh và có thể đăng nhập nó cho việc sử dụng trong tương lai.custom exception to make it clear what is being caught in the catch block and to understand the exception in a better way. The custom exception class inherits properties from the PHP exception's class where you can add your custom functions too. To easily understand the exceptions we can use custom exceptions and can log it for the future use.

Nếu bạn chỉ muốn ghi tin nhắn, bạn có thể làm điều đó ở sau:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
3

Nếu bạn muốn chụp các thông báo lỗi cụ thể có thể dễ hiểu, bạn có thể sử dụng:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
4

Code:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
5

Output:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
6

Explanation::

Ví dụ trên là kiểm tra loại, chúng tôi có hai biến tên và tuổi. Giả sử $ name là loại chuỗi và $ AGE là số nguyên loại và chúng tôi cho rằng chúng tôi có thể nhận được bất kỳ loại giá trị nào làm đầu vào sẽ gây ra lỗi. name and age . Let's assume $name is of type string and $age is of type integer and we assumed that we might get any type of value as input which would raise an error.

  • Chúng tôi đã tạo một chức năng gọi là tyecheck để kiểm tra loại biến với ngoại lệ. Nếu điều kiện thất bại, nó sẽ ném một ngoại lệ với một thông báo ngoại lệ mà chúng tôi đã tùy chỉnh.

  • Chúng tôi đã tạo một lớp

    try 
    { 
        // Code that may throw an Exception or Error. 
    } catch (Throwable $t) 
    { 
       // Executed only in PHP 7 and more
    }
    0 để tạo một trình xử lý ngoại lệ tùy chỉnh với một hàm gọi là
    try 
    { 
        // Code that may throw an Exception or Error. 
    } catch (Throwable $t) 
    { 
       // Executed only in PHP 7 and more
    }
    1 sẽ được gọi là khi một ngoại lệ xảy ra.

  • Ở đây, chúng tôi đã gọi hàm tyecheck bên trong một khối thử để nếu gặp bất kỳ lỗi nào, nó có thể bị bắt trong khối bắt.

#5 nhiều ngoại lệ

Bạn cũng có thể xử lý nhiều ngoại lệ trong một khối bắt bằng cách sử dụng ống '|' Biểu tượng như thế này:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
7

#6 Trình xử lý ngoại lệ toàn cầu

Trong bộ xử lý ngoại lệ toàn cầu, nó đặt trình xử lý ngoại lệ mặc định nếu một ngoại lệ không bị bắt trong một khối thử/bắt. Nếu không có khối nào khác được gọi hàm set_exception_handler có thể đặt một hàm sẽ được gọi ở nơi đánh bắt. Việc thực thi sẽ dừng sau khi ngoại lệ_handler được gọi.Global Exception Handler, it sets the default exception handler if an exception is not caught within a try/catch block. If no other block is invoked the set_exception_handler function can set a function which will be called in the place of catch. Execution will stop after the exception_handler is called.

Set_Exception_Handler Cú pháp:

try 
{ 
    // Code that may throw an Exception or Error. 
} catch (Throwable $t) 
{ 
   // Executed only in PHP 7 and more
}
2): Có thể gọi được

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
8

#7 Bắt không bắt giữ

Trước Php phiên bản 8, nếu bạn muốn bắt một ngoại lệ, bạn sẽ cần lưu trữ nó trong một biến số không phân biệt việc sử dụng nó. Bạn thường phải chỉ định loại bất cứ khi nào bạn sử dụng ngoại lệ bắt. Với ngoại lệ bắt không bắt giữ này, bạn có thể bỏ qua biến.Non-Capturing Catch exception, you can ignore the variable.

Example:

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}
9

Bạn có thể đặt nó theo cách này trong Php 8:

interface Throwable
    |- Error implements Throwable
        |- CompileError extends Error
            |- ParseError extends CompileError
        |- TypeError extends Error
            |- ArgumentCountError extends TypeError
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error
    |- Exception implements Throwable
        |- ClosedGeneratorException
        |- DOMException
        |- ErrorException
        |- IntlException
        |- LogicException
            |- BadFunctionCallException
                |- BadMethodCallException
            |- DomainException
            |- InvalidArgumentException
            |- LengthException
            |- OutOfRangeException
        |- PharExceptionaddition
        |- ReflectionException
        |- RuntimeException
            |- mysqli_sql_exception
            |- OutOfBoundsException
            |- OverflowException
            |- PDOException
            |- RangeException
            |- UnderflowException
            |- UnexpectedValueException
        |- Custom Exception
0

Summary:

Ở đây chúng tôi đã giải thích việc sử dụng cơ bản các ngoại lệ và cách thực hiện chi tiết. Bạn có thể nhanh chóng theo dõi các lỗi và sửa các ngoại lệ đã được ném vào mã của bạn. Tôi hy vọng blog này có thể hữu ích cho bạn để tìm hiểu ngoại lệ là gì và cách sử dụng chính xác của nó.

Nếu bạn muốn theo dõi mã PHP của mình, bạn có thể thử Atatus ở đây.

Chúng ta có thể bắt được lỗi nghiêm trọng trong PHP không?

Trong Php 7, các lỗi nghiêm trọng hiện là ngoại lệ và chúng ta có thể xử lý chúng rất dễ dàng. Lỗi gây tử vong dẫn đến một ngoại lệ lỗi đang bị ném. Bạn cần xử lý các lỗi không gây tử vong với chức năng xử lý lỗi. Dưới đây là một ví dụ về việc bắt một lỗi nghiêm trọng trong Php 7.1.fatal errors are now exceptions and we can handle them very easily. Fatal errors result in an error exception being thrown. You need to handle non-fatal errors with an error-handling function. Here is an example of catching a fatal error in PHP 7.1.

Làm thế nào để bạn bắt lỗi trong PHP?

Hãy thử, ném và bắt..
Hãy thử - một chức năng sử dụng một ngoại lệ phải nằm trong khối "thử".Nếu ngoại lệ không kích hoạt, mã sẽ tiếp tục như bình thường.....
Ném - Đây là cách bạn kích hoạt một ngoại lệ.....
Bắt - Khối "bắt" lấy một ngoại lệ và tạo một đối tượng chứa thông tin ngoại lệ ..

Tại sao xử lý ngoại lệ được sử dụng trong PHP?

Xử lý ngoại lệ được sử dụng để thay đổi luồng thông thường của thực thi mã nếu xảy ra một điều kiện lỗi (ngoại lệ) được chỉ định.Điều kiện này được gọi là một ngoại lệ.Đây là những gì thường xảy ra khi một ngoại lệ được kích hoạt: trạng thái mã hiện tại được lưu.to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: The current code state is saved.

Phát biểu nào sau đây gọi lớp ngoại lệ?

Phát biểu nào sau đây gọi lớp ngoại lệ?Giải thích: ném ngoại lệ mới ();Kích hoạt một ngoại lệ và mỗi người ném ném phải có ít nhất một người bắt được.throw new Exception(); trigger an exception and each “throw” must have at least one “catch”.