Analysis of error handling and exception handling mechanisms in PHP

  • 2020-05-17 04:54:27
  • OfStack

Ex. :
 
<?php 
$a = fopen('test.txt','r'); 
// The file is opened without judgment, and an error is reported if the file does not exist  
?> 

The correct way to write it is as follows:
 
<?php 
if(file_exists('test.txt')){ 
$f=fopen('test.txt','r'); 
// Close after use  
fclose($f); 
} 
?> 

1. Three methods of PHP error handling: A, simple die() statements;
Equivalent to exit ();
Ex. :
 
if(!file_exists('aa.txt')){ 
die(' File does not exist '); 
} else { 
// Perform operations  
} 
// If the above die() It's triggered. So here echo The connection is not executed  
echo 'ok'; 

Write it succinctly:
 
file_exits('aaa.txt') or die(' File does not exist '); 
echo 'ok'; 

B, custom errors, and error triggers

1. Error handler (custom error, 1 for syntax error handling)
Create a custom error function (handler) that must be able to handle at least two arguments (error_level and errormessage), but can accept up to five arguments (error_file, error_line, error_context)
Grammar:
 
function error_function($error_level,$error_message,$error_file,$error_line,$error_context) 
// Once you've created it, you need to rewrite it set_error_handler(); function  
set_error_handler('error_function',E_WARNING);// Here, error_function Corresponding to the custom processor name created above, no 2 Is the error level using the custom fault handler;  

Error reporting level (understand)

These error reporting levels are different types of errors that the error handler is designed to handle:

value constant describe 2 E_WARNING Non-fatal run-time error. Do not suspend script execution. 8 E_NOTICE

Run - time notice.

Script discovery can occur, but it can also occur when the script is running normally.

256 E_USER_ERROR Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error(). 512 E_USER_WARNING Non-fatal user-generated warnings. This is similar to E_WARNING set by the programmer using the PHP function trigger_error(). 1024 E_USER_NOTICE User-generated notifications. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error(). 4096 E_RECOVERABLE_ERROR Fatal error that can be caught. Similar to E_ERROR, but can be captured by a user-defined handler. (see set_error_handler ()) 8191 E_ALL

All errors and warnings except level E_STRICT.

(in PHP 6.0, E_STRICT is part 1 of E_ALL)


2. Error trigger (1 is generally used to handle logical errors)
Requirements: for example, to receive an age, if the number is greater than 120, it is considered an error
Traditional methods:
 
if($age>120){ 
echo ' Age mistake ';exit(); 
} 

Using triggers:
 
if($age>120){ 
//trigger_error(' The error message '[ . ' Error level ']); Here the error level is optional and is used to define the level of the error  
// User-defined levels include the following 3 A: E_USER_WARNING  , E_USER_ERROR  , E_USER_NOTICE 
trigger_error(' Age mistake ');// Here is the default error handling for the called system, and we can also use a custom handler  
} 
// Custom processor, same as above  
function myerror($error_level,$error_message){ 
echo 'error text'; 
} 
// You also need to change the system's default handler  
set_error_handler('myerror',E_USER_WARNING);// Same as above, no 1 The parameters are the name of the custom function, the first 2 The error levels are usually below 3 A: E_USER_WARNING  , E_USER_ERROR  , E_USER_NOTICE 】  
// Now reuse trigger_error Then you can use your custom error handler  

Exercises:
 
<?php 
date_default_timezone_set('PRC'); 
function myerror($error_level,$error_message){ 
$info= " Error no. : $error_level\n"; 
$info.= " Error message: $error_message\n"; 
$info.= ' Time: '.date('Y-m-d H:i:s'); 
$filename='aa.txt'; 
if(!$fp=fopen($filename,'a')){ 
' Create a file '.$filename.' failure '; 
} 
if(is_writeable($filename)){ 
if(!fwrite($fp,$info)){ 
echo ' Write file failed '; 
} else { 
echo ' Error message successfully logged '; 
} 
fclose($fp); 
} else { 
echo ' file '.$filename.' Do not write '; 
} 
exit(); 
} 
set_error_handler('myerror',E_WARNING); 
$fp=fopen('aaa.txt','r'); 
?> 

C, error log
By default, php sends error records to the server's error logging system or file based on the error_log configuration in php.ini. You can send error records to files or remote destinations by using the error_log() function.
Grammar:
error_log(error[,type,destination,headers])
Part 1 of type is usually used as a 3 to indicate that an error message is appended to the end of the file without overwriting the original content
destination represents a destination, either a file or a remote destination
Such as: error_log (" $error_info ", 3, "errors. txt");
2. PHP exception handling
1. Basic grammar
 
try{ 
// Code that may have errors or exceptions  
//catch  capture  Exception is php A defined exception class  
} catch(Exception $e){ 
// For exception handling, methods:  
//1 Take care of yourself  
//2 , do not handle it, throw it again  
} 

2. The processing procedure shall include:
Try - functions that use exceptions should be in the "try" code block. If no exception is fired, the code continues to execute as usual. But if the exception is triggered, an exception is thrown.
Throw - this specifies how to trigger an exception. Every "throw" must correspond to at least one "catch"
The Catch - "catch" code block catches the exception and creates an object that contains the exception information
Let's fire an exception:
 
<?php 
// Create ejectable 1 It's an abnormal function  
function checkNum($number){ 
if($number>1){ 
throw new Exception("Value must be 1 or below"); 
} 
return true; 
} 
// in  "try"  An exception is fired in a code block  
try{ 
checkNum(2); 
// If the exception is thrown, then the following 1 Lines of code will not be output  
echo 'If you see this, the number is 1 or below'; 
}catch(Exception $e){ 
// Catch exceptions  
echo 'Message: ' .$e->getMessage(); 
} 
?> 

The above code will get an error like this:
Message: Value must be 1 or below
Example explanation:
The code above throws an exception and catches it:
Create the checkNum() function. It detects if the number is greater than 1. If so, an exception is thrown.
The checkNum() function is called in the "try" code block.
The exception in the checkNum() function is thrown
The "catch" code block receives the exception and creates an object containing the exception information ($e).
By calling $e- from this exception object > getMessage(), which outputs an error message from the exception
However, to follow the principle that there must be one catch per throw, you can set up a top-level exception handler to handle missed errors.
The set_exception_handler() function can be set to handle all user-defined functions that do not catch exceptions
 
// Set up the 1 Two top-level exception handlers  
function myexception($e){ 
   echo 'this is top exception'; 
} // Modify the default exception handler  
set_exception_handler("myexception"); 
try{ 
  $i=5; 
  if($i<10){ 
    throw new exception('$i must greater than 10'); 
  } 
}catch(Exception $e){ 
  // Handle exceptions  
  echo $e->getMessage().'<br/>'; 
  // Do not handle the exception, continue to throw  
  throw new exception('errorinfo'); // You can also use throw $e  Keep the original error message ; 
} 

Create a custom exception class
 
class customException extends Exception{ 
  public function errorMessage(){ 
    //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; 
  } 
} 
// use  
try{ 
  throw new customException('error message'); 
}catch(customException $e){ 
  echo $e->errorMsg(); 
} 

You can use multiple catch to return error messages in different situations
 
try{ 
  $i=5; 
  if($i>0){ 
    throw new customException('error message');// Use custom exception class handling  
  } if($i<-10){ 
    throw new exception('error2');// Use system default exception handling  
  } 
}catch(customException $e){ 
  echo $e->getMessage(); 
}catch(Exception $e1){ 
  echo $e1->getMessage(); 
} 

Exception rule
Code that requires exception handling should be placed in the try code block to catch potential exceptions. Each try or throw code block must have at least one corresponding catch code block. Different kinds of exceptions can be caught using multiple catch code blocks. You can throw the (re-thrown) exception again in the catch code block within the try code. In short: if an exception is thrown, it must be caught.

Related articles: