Php, can exceptions be dropped to 2 levels?

I know this is strange, but there are development mode errors and production mode errors in my code. This is the i function:

private function error($message, $mysql_error = null){ if( DEVELOPMENT_MODE ){ $exp = new Exception(); $trace = $exp -> getTrace(); array_shift( $trace ); // removes this functions from trace $data["Error Mg"] = $message; $data["MySQL Er"] = ( is_null ( $mysql_error ) ) ? "" : $mysql_error; array_unshift($trace, $data ); fkill( $trace ); // formats array and then dies } else{ throw new Exception ( $data ); } } 

I wrote this function in my database class, so if an error occurs, I do not need to provide a check if we are in development mode or not!

So, I thought I could supplant the reusable code. However, since I selected an exception from this function, I mainly use a function that will return an error. Pretty useless in production mode.

I will need to do this every time I want to use it:

 try{ $this -> error( "Invalid Link After Connect.", mysql_error () ); } catch ( Exception $exp ){ throw $exp; } 

ANSWER THAN SIMPLY

 $this -> error( "Invalid Link After Connect.", mysql_error () ); 

to avoid writing try ... catch block for each error function that I want to call ... is there a way to throw an exception at 2 levels?

+4
source share
3 answers

The exception will automatically move through the call chain until it reaches the highest level. If it does not get there, the program terminates due to an uncaught exception. The whole point of exceptions is to be able to create errors. You do not need to throw harder or do something special to “throw 2 levels”, which he does by definition.

+13
source

Just omit the try / catch . Exceptions are automatically propagated until something catches them; you don’t need to explicitly forward them at each level of the call stack.

It...

 try{ $this -> error( "Invalid Link After Connect.", mysql_error () ); } catch ( Exception $exp ){ throw $exp; } 

exactly equivalent to this:

 $this -> error( "Invalid Link After Connect.", mysql_error () ); 
+10
source

Using multiple catch blocks use an admin table that has a field

 Mode Value 0 Production 1 Debug 

the first catch is executed that matches the exception

Example

  try { if (!$bDBConnection && $row['mode'] ==0 ) { throw new Produciton_DBException("Problem with Database"); } else { throw new Debug_DBException("Problem with Database"); } } catch(Produciton_DBException $e) { // display suitable error messages } catch(Debug_DBException $ex) { // Exception falls through until a match is found } 
+1
source

Source: https://habr.com/ru/post/1400954/


All Articles