- How to return errors from PHP method?
- 6 Answers 6
- Php print array in error log php
- How to echo/print a nicely formatted array to the modx log?
- Logs an entire array using Monolog
- Error log print array
- PHP print_r large array to variable not working
- Управление выводом ошибок PHP
- Вывод ошибок в браузере
- В htaccess
- Запись ошибок в лог файл
- Отправка ошибок на e-mail
- Пользовательские ошибки
- Результат:
- How to throw an array exception in php
- 4 Answers 4
- Print_r() to PHP error_log() not working. (non-printing characters)
How to return errors from PHP method?
I have a save method in my User class. If the save method encounters validation errors it returns an array of errors that I display to the user. However this means in my code I have to write:
6 Answers 6
Use try . catch syntax.
try < $user->save(); > catch (Exception $e) < echo 'Caught exception: ', $e->getMessage(), "\n"; >
So within my save method, if the error message array is populated, I throw an exception? How can I include the multiple error messages in the exception? So I can display them to the user.
I would throw an exception in the event that save() runs into any problems.
If you want to provide an array of validation errors, your could subclass Exception and provide a mechanism for storing the validation errors.
A custom Exception subclass will also help you differentiate between exceptions your code throws explicitly (which you’d like to catch) and exceptions that you didn’t expect (which should be fatal).
class UserException extends Exception < private $userMessages; public function __construct($message = "", $code = 0, Exception $previous = null, array $userMessages = null) < parent::__construct($message, $code, $previous); if ($userMessages === null) < $this->userMessages = array(); > else < $this->userMessages = $userMessages; > > public function getUserMessages() < return $this->userMessages; > >
Here’s a silly version of a User class that always throws an Exception on save() .
$user = new User(); try < $user->save(); > catch (UserException $e) < foreach ($e->getUserMessages() as $message) < print $message . "\n"; >>
You could also accomplish something like this by populating the Exception’s $message with, say a semi-colon-delimited list of messages. You could even build a list of constants for error types, then combine them as a bitmask and use that for the Exception’s $code. The advantage of these options is you would be using the built in members and not adding anything extra.
Php print array in error log php
Solution: If you check the logger interface (https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php) you will see all of the logging methods gets message as a string, thus you get a warning when you try to log with a variable type other than string.Solution 1: in function add 2 nd argument for return output value, see below sample code Solution 2: You don’t need the tags, just will do the job, as of Revo version 2.3.3 at any rate.
How to echo/print a nicely formatted array to the modx log?
in print_r() function add 2 nd argument TRUE for return output value, see below sample code
$log = "
"; $log .= print_r($formdata, true); $log .= ""; $this->modx->log(modX::LOG_LEVEL_ERROR, 'Form Data = ' . $log);
You don’t need the «
" - "» tags, just
$modx->log(xPDO::LOG_LEVEL_ERROR, «Form Data = » . print_r($formdata,true),»,’mySnippet’);
will do the job, as of Revo version 2.3.3 at any rate.
Logs an entire array using Monolog
If you check the logger interface (https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php) you will see all of the logging methods gets message as a string, thus you get a warning when you try to log with a variable type other than string.
I tried to use a processor to format the array in a custom manner, but as expected the processor is triggered after you send the variable to logger interface.
The dirtiest way of logging an array may be any of those for your choice;
$logger->info(json_encode($array)); $logger->info(print_r($array, true)); $logger->info(var_export($array, true));
On the other hand you may want to format your array in a single proccessor to centralize your formatting logic with DRY principles.
Json encode array -> Send as Json String -> json decode to array -> format -> json encode again
public function processRecord(array $record) < try < //parse json as object and cast to array $array = (array)json_decode($record['message']); if(!is_null($array)) < //format your message with your desired logic ksort($array); $record['message'] = json_encode($array); >> catch(\Exception $e) < echo $e->getMessage(); > return $record; > >
Register request processor in your config.yml or services.yml, see the tags node for registering the processor for a custom channel.
services: monolog.formatter.session_request: class: Monolog\Formatter\LineFormatter arguments: - "[%%datetime%%] %%channel%%.%%level_name%%: %%message%%\n" monolog.processor.session_request: class: Acme\WebBundle\CustomRequestProcessor arguments: [] tags: -And in the controller log your array as a json string,
get('monolog.logger.testchannel'); $array = array(3=>"hello" , 1=>"world", 2=>"sf2"); $logger->info(json_encode($array)); return $this->render('AcmeWebBundle:Default:index.html.twig'); > >
Now you can format and log your array as your desire in a central request processor without sorting/formating/walking on the array in your every controller.
Error log print array
error_log( print_r($multidimensionalarray, TRUE) );PHP print_r large array to variable not working
The problem is that internally, print_r($arr, true) simply uses output buffering as in the second example. So behind the scenes, both methods are equivalent. But why is output buffering not working?
Intrigued, I replaced $arr = get_large_array(); with $arr = array(); . To my surprise, file.txt was created and there was no output. I had an idea. I changed $arr back to the large array, ran the code, and scrolled down to the end of the output. Sure enough, it was being truncated. I looked in the error log, and there were 20 or so «out of memory» errors occurring on the print_r line. In dealing with the large array, print_r ran out of memory, crashed and ignored the file_put_contents and the ob_end_clean , displaying the aforementioned symptoms.
For me, the solution was to increase the memory limit:
ini_set('memory_limit', '1024M');
Error log print array Code Example, Queries related to “error log print array” · error log php array · error log array · print array in error log php · error_log with array · php
Управление выводом ошибок PHP
PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:
- E_ALL – все ошибки,
- E_ERROR – критические ошибки,
- E_WARNING – предупреждения,
- E_PARSE – ошибки синтаксиса,
- E_NOTICE – замечания,
- E_CORE_ERROR – ошибки обработчика,
- E_CORE_WARNING – предупреждения обработчика,
- E_COMPILE_ERROR – ошибки компилятора,
- E_COMPILE_WARNING – предупреждения компилятора,
- E_USER_ERROR – ошибки пользователей,
- E_USER_WARNING – предупреждения пользователей,
- E_USER_NOTICE – уведомления пользователей.
Вывод ошибок в браузере
error_reporting(E_ALL); ini_set('display_errors', 'On');
В htaccess
php_value error_reporting "E_ALL" php_flag display_errors On
На рабочем проекте вывод ошибок лучше сделать только у авторизированного пользователя или в крайнем случаи по IP.
Запись ошибок в лог файл
error_reporting(E_ALL); ini_set('display_errors', 'Off'); ini_set('log_errors', 'On'); ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');
Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:
Order Allow,Deny Deny from all
Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):
Order Allow,Deny Deny from all
Отправка ошибок на e-mail
Ошибки можно отправлять на е-mail разработчика, но приведенные методы не работает при критических ошибках.
Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.
register_shutdown_function('error_alert'); function error_alert() < $error = error_get_last(); if (!empty($error)) < mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true)); >>
Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.
Второй метод использует «пользовательский обработчик ошибок», поэтому в браузер ошибки выводится не будут.
function error_alert($type, $message, $file, $line, $vars) < $error = array( 'type' =>$type, 'message' => $message, 'file' => $file, 'line' => $line ); error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com'); > set_error_handler('error_alert');
Пользовательские ошибки
PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error() :
trigger_error('Пользовательская ошибка', E_USER_ERROR);
Результат:
Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
- E_USER_ERROR – критическая ошибка,
- E_USER_WARNING – не критическая,
- E_USER_NOTICE – сообщения которые не являются ошибками,
- E_USER_DEPRECATED – сообщения о устаревшем коде.
How to throw an array exception in php
The problem, however, is that $_r[‘errors’] is an ARRAY and it get $e->getMessage() just prints it as «Array». How can I modify this code to access the array?
4 Answers 4
The problem is that You’re trying to merge array with a string. It’ll always end like this.
Maybe You should pass to exception an array, so You can later make use of it?
params = $params; > public function getParams() < return $this->params; > > // later it can be used like this: try < $exception = new myException('Error!'); $exception->setParams(array('status' => 1, 'errors' => array()); throw $exception; > catch (myException $e) < // . >?>
This is bad form as it breaks the basic interface of exceptions. If you need to pass some values — just add a method that collects and stores them.
To convert a complex data-structure like an array into a string (e.g. for error messages), you can make use of print_r Docs and setting it’s second parameter to TRUE :
throw new Exception(json_encode(['type'=>'error','isExit'=>'true','title'=>'SystemConfigError']));
catch (Exception $error) < var_dump(json_decode($error->getMessage(),JSON_OBJECT_AS_ARRAY)); >
so your example code is kinda bad, but assuming
$_r['errors'] = array( 'Message 1', 'Message 2', 'Message 3', 'Message 4', 'Message 5', );
$error_message = "Error received for " . $service . ": \n" . impolode("\n", $_r['errors']) . "\n" . "Message received: " . $_r['errors']; throw new My_Exception($error_message);
The key is taking your array of error messages and concatenating them all together with newlines (or whatever)
But I kinda agree with the comment that you may be using the Exception framework wrong. Can you post what you are trying to do?
The general rule of thumb is that you throw an exception for each unique event. You dont collect a bunch of error messages and then throw them all at once.
Print_r() to PHP error_log() not working. (non-printing characters)
I have a static method in a helper class Utility::error_log() for helping us gracefully debug HUGE objects in PHP. The method, and it’s helper-method Utility::toArray() are below:
static function error_log($message, $data=null, $max=2) < if(is_array($data) || is_object($data)) $data = print_r(self::toArray($data, $max),true); if(is_array($message) || is_object($message)) $message = print_r(self::toArray($message, $max),true); if(!empty($data)) $data = "\n".$data; if (!strstr($message, PHP_EOL)) $message = str_pad(" ".$message." ", 50,'=',STR_PAD_BOTH); error_log($message.$data); >static function toArray($object, $max = 2, $current = 0) < if($current >$max) return ucfirst(gettype($object)).'( . )'; $current++; $return = array(); foreach((array) $object as $key => $data) if (is_object($data)) $return[$key] = self::toArray($data, $max, $current); elseif (is_array($data)) $return[$key] = self::toArray($data, $max, $current); else $return[$key] = $data; return $return; >
Now that may be a bit to look at, but the gist is, toArray makes a HUGE object (lots of recursion) orders of a magnitude smaller, and returns all properties as either arrays or strings. Much easier to work with. The idea being that print_r($array,true) then makes the array a string, and we log it. This doesn’t work as expected, however. The result is:
[05-Apr-2013 05:29:00] ==================================== PERSISTING SUITS & SHIRTS =================================== Array ( [
Array ( [BRS\PageBundle\Entity\Pageroot_folder_name] => Pages [id] => 43 [title] => Suits & Shirts [depth_title] => Suits & Shirts [description] => ( . AND SO ON . )
Before you say it is an error_log() length limitation, I will mention that I can successfully $data = var_export($data,true) and send the result to error_log() with no problems:
[05-Apr-2013 06:00:08] ==================================== PERSISTING SUITS & SHIRTS =================================== array ( '' . "\0" . 'BRS\\PageBundle\\Entity\\Page' . "\0" . 'root_folder_name' => 'Pages', 'id' => 43, 'title' => 'Suits & Shirts', 'depth_title' => 'Suits & Shirts', 'description' => ( . AND SO ON . )
What is the problem? Why does it work with var_export($data,true) , and print_r($data,false) , but not with print_r($data,true) ??