简体   繁体   中英

Custom messages for php exception handling

I'm using an external file with $errmsg array for displaying errors, like:

'app_init' => 'Cannot initialize application',

Using conditionals, I call the function to display the message on failure:

if(!$condition)
{
$arraywithmessages->functionforfiltering($err,'app_init',$aim);
}

...where $err is the array of messages, and $aim is predefined method of publishing error (e-mail, view, etc...)

Now I'd like to make use of Exception Handling, but I don't know where to start. Can anyone help? This doesn't seem to work:

try {
if (!$condition) {
throw new Exception('app_init');
}
// continue
} catch (Exception $e) {
$arraywithmessages->functionforfiltering($err,$e->getMessage(),$aim);
}

I don't know exactly what you want to achive but you should remember that try, catch should be used wisely. It should be used for Exceptional situations only. If you don't use them in that way then it's GOTO code.

About exceptions, remmeber that you can extend Exception class and make your own exceptions and catch them in multiple catch blocks, there is also finally block.

About the constructor of Exception. It has the second param which is $code you can use it to show proper message.

$err = array(0x1 => 'my error app init');

try {
if (!$condition) {
    throw new Exception('app_init', 0x1);
}
// continue
} catch (Exception $e) {
  echo $err[$e->getCode()]; //it shouldn't be only echo it should do some tries to fix the code close streams etc. not just echo.
}

There is also function set_exception_handler(). which:

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Consider using it. There are a lot of things that can be found in manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM