I have a class and the commented line is failing (clearly because I don't need the $ before displayname), however I ended up having to put a bunch of echo statements in to figure that out because an error isn't being thrown.
I'm hoping there is a way.
class RegisterModel {
var $displayname;
...
function RegisterModel() {
try {
if (empty($_POST) === false) {
// THIS LINE IS FAILING ... BUT I'M NOT GETTING AN ERROR
// I KNOW WHY IT'S FAILING ... BUT I WANT AN ERROR TO THROW
$this->$displayname = $_POST['displayname'];
...
}
}
catch (Exception $e) {
echo $e->getMessage();
}
}
}
Should the error be getting thrown into the catch and I'm just not using it right? Is there some global setting I need to set so that the errors are thrown?
set_error_handler(function($errno ,$errstr,$errfile,$errline,$errcontext){
if($errno & error_reporting()) throw new Exception($errstr,$errno);
});
Keep in mind you want to set error_reporting to your desired level.
You can try adding:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If this displays the error, you have a potential run-time configuration error. You could adjust your configuration accordingly if it's impossible. You can look at the various error-related variables defined here.
Related
Came across this today, not sure how to solve it.
I want to catch an E_WARNING level error issued by hex2bin().
I thought I might be able to use a try()catch() exception method but it did not work.
try {
$foo = hex2bin($bar);
}
catch (Exception $e) {
die('Custom message');
}
The standard E_WARNING that is issued is, of course:
Warning: hex2bin(): Input string must be hexadecimal string
In this particular situation I do not want to use the standard methods to disable errors, such as:
error_reporting(-1);
error_reporting(E_ALL);
ini_set("display_errors", 1);
Nor do I want to suppress the error using a #hex2bin method.
I actually want to have a custom error displayed, but I just do not seem to be able to find a way to catch when hex2bin throws an error.
You can check the input value to verify that it is hex before passing it to the hex2bin method.
if (ctype_xdigit($bar) && strlen($bar) % 2 == 0) {
$foo = hex2bin($bar);
} else {
//display error here
}
Per the documentation, hex2bin returns:
the binary representation of the given data or FALSE on failure.
That means you can do something like this if you want to use it in a try/catch block:
try {
$foo = #hex2bin($bar);
if(false === $foo) {
throw new Exception("Invalid hexedecimal value.");
}
} catch(Exception $e) {
echo $e;
}
Yes, hex2bin is suppressed. You can remove the # if you set error_reporting to suppress warnings.
Alternatively, you can check the type of $foo with ctype_xdigit() prior to using hex2bin().
I want to receive the error message in php before it gets executed. Basicly what i mean is that if I would have a bad code:
// This code is incorrect, I want to receive the error before it gets handled!
$some_var = new this_class_is_not_made;
Now that class does not exist, so it would be handles by the default error handler in php. But I want to disable the normal error handler and create my own.
Another example:
somefunction( string some_var ); // some_var misses the variable prefix. ( $ )
Example error message:
Fatal error: function 'some_var' is not defined in line: $x!
And this error would be: somefunction( string some_var );
But how would I receive the messages but also disable the normal error system?
EDIT: Making the error system execute a user-defined function
// I would want the error system to execute a function like this:
function(string $errorMessage, int $error_code){
if($error_code < 253){ return "Fatal error"; }
if($error_code < 528 && $error_code > 253){ return "Warning"; }
}
Answer found: By: ShiraNai7
try
{
// Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
// Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
// Executed only in PHP 5, will not be reached in PHP 7
}
In PHP 7.0.0 or newer the code will throw Error exception if this_class_is_not_made doesn't exist.
try {
$some_var = new this_class_is_not_made;
} catch (Error $e) {
echo $e->getMessage();
}
Note that that this will also catch any other Error exceptions in case this_class_is_not_made does exist and causes some other error along the way.
In PHP versions prior to 7.0.0 you're out of luck - fatal errors always terminate the main script.
It might be a better idea to use class_exists() instead:
if (class_exists('this_class_is_not_made')) {
$some_var = new this_class_is_not_made;
}
This works in all PHP versions that support classes.
If I include a file in to php. If there is any fatal error in that php then is there any way to skip that .
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on somefile.php
?>
I need to include this somefile.php file. It may return fatal error
for some host. I want to skip this file for those host.
Please Advice me.
With this, you can define your own continuation function that will take over in case of a fatal error. This uses register_shutdown_function() to intercept the fatal error.
Usage:
function my_continuation_func($filename, $arg2) {
// On fatal error during include, continue script execution from here.
// When this function ends, or if another fatal error occurs,
// the execution will stop.
}
include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();
If a fatal error occurs (like a parse error), script execution will continue from my_continuation_func(). Otherwise, include_catch() returns true if there was an error during parsing.
Any output (like echo 'something';) from the include() is treated as an error. Unless you enabled output by passing true as the third argument to include_try().
This code automatically takes care of possible working directory changes in the shutdown function.
You can use this for any number of includes, but the second fatal error that occurs cannot be intercepted: the execution will stop.
Functions to be included:
function include_try($cont_func, $cont_param_arr, $output = false) {
// Setup shutdown function:
static $run = 0;
if($run++ === 0) register_shutdown_function('include_shutdown_handler');
// If output is not allowed, capture it:
if(!$output) ob_start();
// Reset error_get_last():
#user_error('error_get_last mark');
// Enable shutdown handler and store parameters:
$params = array($cont_func, $cont_param_arr, $output, getcwd())
$GLOBALS['_include_shutdown_handler'] = $params;
}
function include_catch() {
$error_get_last = error_get_last();
$output = $GLOBALS['_include_shutdown_handler'][2];
// Disable shutdown handler:
$GLOBALS['_include_shutdown_handler'] = NULL;
// Check unauthorized outputs or if an error occured:
return ($output ? false : ob_get_clean() !== '')
|| $error_get_last['message'] !== 'error_get_last mark';
}
function include_shutdown_handler() {
$func = $GLOBALS['_include_shutdown_handler'];
if($func !== NULL) {
// Cleanup:
include_catch();
// Fix potentially wrong working directory:
chdir($func[3]);
// Call continuation function:
call_user_func_array($func[0], $func[1]);
}
}
Fatal means fatal ...
There is no way to recover from a fatal error.
You can use register_shutdown_function.
<?php
function echoOk()
{
echo "OK";
}
register_shutdown_function(function ()
{
$error = error_get_last();
// to make sure that there is any fatal error
if (isset($error) &&
($error['type'] == E_ERROR
|| $error['type'] == E_PARSE
|| $error['type'] == E_COMPILE_ERROR
|| $error['type'] == E_CORE_ERROR))
{
echoOk();
}
});
include "somefile.php";
echoOk();
But you can do it only once. Any further fatal error will stop execution.
PHP won't tolerate with Fatal Errors. Best to check the included file and solve it.
Actually, you can try looking at register-shutdown-function, but it's not recommended to run away from your problems.
Yes, there is. It can be done through a simple if statement
You Have:
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on
?>
Try This:
<?php
if(include "somefile.php"){
// echo do something if success
}else{
echo "OK";
}
edit: I missed the word fatal. As stated, you can't recover from a fatal error. If it is just an exception the hastly writen response below will work.
Including another php module is the same as that code being inserted inline, so a simple try-catch statement should work:
<?php
try {
include "somefile.php";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "OK";
?>
Try to set a set_error_handler() function that doesn't die on fatal errors, but instead Apache crashed. In other words, PHP needs to die so that the system doesn't.
See this LINK
Fatal Error means there is something seriously wrong with the including code. As #Orangepill said there is no way to stop this fatal error message popping up. Please go through your coding and find the error.
I'm calling a method that I know could cause an error and I'm trying to handle the error by wrapping the code in a try/catch statement...
class TestController extends Zend_Controller_Action
{
public function init()
{
// Anything here happens BEFORE the View has rendered
}
public function indexAction()
{
// Anything `echo`ed here is added to the end of the View
$model = new Application_Model_Testing('Mark', 31);
$this->view->sentence = $model->test();
$this->loadDataWhichCouldCauseError();
$this->loadView($model); // this method 'forwards' the Action onto another Controller
}
private function loadDataWhichCouldCauseError()
{
try {
$test = new Application_Model_NonExistent();
} catch (Exception $e) {
echo 'Handle the error';
}
}
private function loadView($model)
{
// Let's pretend we have loads of Models that require different Views
switch (get_class($model)) {
case 'Application_Model_Testing':
// Controller's have a `_forward` method to pass the Action onto another Controller
// The following line forwards to an `indexAction` within the `BlahController`
// It also passes some data onto the `BlahController`
$this->_forward('index', 'blah', null, array('data' => 'some data'));
break;
}
}
}
...but the problem I have is that the error isn't being handled. When viewing the application I get the following error...
( ! ) Fatal error: Class 'Application_Model_NonExistent' not found in /Library/WebServer/Documents/ZendTest/application/controllers/TestController.php on line 23
Can any one explain why this is happening and how I can get it to work?
Thanks
use
if (class_exists('Application_Model_NonExistent')) {
$test = new Application_Model_NonExistent;
} else {
echo 'class not found.';
}
like #prodigitalson said you can't catch that fatal error.
An error and an exception are not the same thing. Exceptions are thrown and meant to be caught, where errors are generally unrecoverable and triggered with http://www.php.net/manual/en/function.trigger-error.php
PHP: exceptions vs errors?
Can I try/catch a warning?
If you need to do some cleanup because of an error, you can use http://www.php.net/manual/en/function.set-error-handler.php
Thats not an exception, thats a FATAL error meaning you cant catch it like that. By definition a FATAL should not be recoverable.
Exception and Error are different things. There is an Exception class, which you are using and that $e is it's object.
You want to handle errors, check error handling in php-zend framework. But here, this is a Fatal error, you must rectify it, can not be handled.
Which would you recommend?
Return an error code, such as E_USER_ERROR from a function, and determine proper message higher up:
function currentScriptFilename()
{
if(!isset($_SERVER['SCRIPT_FILENAME']))
{
//This?
return E_USER_ERROR;
}
else
{
$url = $_SERVER['SCRIPT_FILENAME'];
$exploded = explode('/', $url);
return end($exploded);
}
}
Execute trigger_error() from the function, with a specific error message:
function currentScriptFilename()
{
if(!isset($_SERVER['SCRIPT_FILENAME']))
{
//Or this?
trigger_error('$_SERVER[\'SCRIPT_FILENAME\'] is not set.', E_USER_ERROR);
}
else
{
$url = $_SERVER['SCRIPT_FILENAME'];
$exploded = explode('/', $url);
return end($exploded);
}
}
I am not sure if I will regret having put a bunch of error messages in my functions further down the line, since I would like to use them for other projects.
Or, would you recommend something totally different?
Do not mix the matters.
Error notification and error handling are different tasks.
You have to use both methods simultaneously.
If you think that $_SERVER['SCRIPT_FILENAME'] availability is worth an error message, you can use trigger error. However PHP itself will throw a notice if you won't check it.
If you want to handle this error, just check this function's return value.
But I would not create a special function for this task.
So,
if (!$filename = basename($_SERVER['SCRIPT_FILENAME']) {
// do whatever you want to handle this error.
}
would be enough
Exceptions could be useful to handle errors, to know if we had any errors occurred.
A simple example:
try {
$filename = basename($_SERVER['SCRIPT_FILENAME'])
if (!$filename) throw new Exception("no filename");
$data = get_some_data_from_db() or throw new Exception("no data");
$template = new Template();
//Exception could be thrown inside of Template class as well.
}
catch (Exception $e) {
//if we had any errors
show_error_page();
}
$template->show();
3.Use exceptions.
If this is the route you are going, I'd rather recommend throwing Exceptions rather then returing an E_ERROR (E_USER_ERROR should be used), as this is just an integer, and possibly a totally valid return for your function.
Advantages:
- Throwing of an Exception cannot be interpreted as anything else then an error by mistake.
- You keep the possibility to add a descriptive error message, even though you don't handle the error at that point/
- You keep a backtrace in your Exception.
- You can catch specific exceptions at specific points, making the decision where in your project a specific type of error should be handled a lot easier.
If not using exceptions which you should be, use trigger_error().
If it is an error you'd like to deal with, try returning FALSE like a lot of the in built functions do.
If you do use exceptions, catch them like this
try {
whatever()
} catch (Exception $e) {
// handle however
}