Table of Contents
Exception
Error
Home Backend Development PHP7 What to do if a global exception/error occurs in PHP

What to do if a global exception/error occurs in PHP

Jul 26, 2021 am 09:28 AM
php

During development, we often need to customize error and exception handling functions to provide more friendly processing tips in different scenarios. Today we will introduce how to use set_exception_handler/set_error_handler to solve exceptions/errors. You can refer to it if necessary.

What to do if a global exception/error occurs in PHP

Exception

If we throw an Exception without try catch capture processing, the system will generate a fatal error and exit the execution after dumping the relevant information. .

throw new Exception("Error Processing Request", 1);

Fatal error: Uncaught exception 'Exception' with message 'Error Processing Request'
Copy after login

set_exception_handler can set a global exception handling function. When the exception is not handled by try catch, the system will hand over the exception to this function for processing

<?php
/**
 * 全局异常处理函数,会捕捉没有被 try catch 处理的异常
 * @param  [type] $exception [description]
 * @return [type]            [description]
 */
function func_exception_handler($exception)
{
    echo "User Exception:" .
        " [" . $exception->getCode() . "]" .
        " message " . $exception->getMessage() .
        " in file " . $exception->getFile() .
        " on line " . $exception->getLine() . PHP_EOL;
}

//如果不设定全局的异常处理函数 且 抛出异常时不使用 try catch 处理则会 fatal error
set_exception_handler("func_exception_handler");

try {
    throw new Exception("我会被 try catch 捕捉处理,不影响执行流程!");
} catch (Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}

throw new Exception("我没有被 try catch 捕捉处理,会被全局 set_exception_handler 处理!");

echo "没有被 try catch 处理的异常在我之前抛出,虽然被 set_exception_handler 但仍然会立刻退出执行,执行不到我哟" . PHP_EOL;
Copy after login

Note: However, because there is still no Exceptions are handled by try catch. After processing, the program will still exit execution and subsequent code will not be executed.

Error

The errors we often encounter in PHP are: ERROR/WARNING/NOTICE

We can use the trigger_error function to trigger errors, and use set_error_handler to define ourselves error handling function.

trigger_error defaults to user-level NOTICE errors, which will not affect the execution process. The code will continue to execute. We can define the error level ourselves when triggered.

Note: set_error_handler is to intercept user-level errors. error, it does not allow the script to exit execution unless you manually implement error level judgment in your own processing code. If interception is not performed, user-level errors will also be handed over to the system's error handling mechanism. The system's error handling mechanism is to exit with an error and continue execution after a warning notice.

trigger_error("notice, go on!", E_USER_NOTICE);

echo "executing!" . PHP_EOL;

trigger_error("warning, go on!", E_USER_WARNING);

echo "executing!" . PHP_EOL;

trigger_error("error, exit!", E_USER_ERROR);

echo "not execute!";
Copy after login

After customizing error handling, the error will no longer be passed to the system for processing

<?php
/**
 * 用户自定义的错误处理
 * @param  [type] $err_no   错误级别
 * @param  [type] $err_msg  错误信息
 * @param  [type] $err_file 错误文件
 * @param  [type] $err_line 错误所在行
 * @return [type]           [description]
 */
function func_error_handler($err_no, $err_msg, $err_file, $err_line)
{
    //trigger_error 默认触发的为 notice 级别的用户错误
    $level = [
        E_USER_ERROR => "Error",
        E_USER_WARNING => "Waring",
        E_USER_NOTICE => "Notice"
    ];

    echo "User {$level[$err_no]}: " .
        " [" . $err_no . "]" .
        " message " . $err_msg .
        " in file " . $err_file .
        " on line " . $err_line . PHP_EOL;

    //如果需要 我们可以手动判断错误级别是否退出执行
    if ($err_no == E_USER_ERROR) {
        exit("fatal error, exit!");
    }
}

set_error_handler("func_error_handler");

trigger_error("notice, go on!", E_USER_NOTICE);

trigger_error("warning, go on!", E_USER_WARNING);

trigger_error("error, exit!", E_USER_ERROR);
Copy after login

Tips:

If an exception is thrown but does not use try catch processing, the system will generate an Fatal errors cause the script to exit execution. set_exception_handler only captures exceptions that are not handled by try catch. Customizing some friendly information output does not prevent fatal errors from occurring. The script will still exit execution.

set_error_handler will intercept the errors triggered by the user for processing instead of submitting them to the system, but it will not automatically identify the error level. We need to manually determine whether it is an ERROR level to exit, or a WARNING or NOTICE level prompts to continue execution.

Recommended learning: php video tutorial

The above is the detailed content of What to do if a global exception/error occurs in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

See all articles