Dispatch an event if any error is occurred in Joomla - php

Is there any way to dispatch an event and call a method when an error is occurred in joomla same as Zend ? I want to log those error in log file. I want to use a single method to catch every error. is it possible ?
Is there any other way to do this except JError, Please suggest.

To log errors to a file, you can use the following:
jimport('joomla.log.log');
// Log errors to specific file.
JLog::addLogger(
array(
'text_file' => 'mod_mymodule.errors.php'
),
JLog::ALL,
'mod_mymodule'
);
This will create the following and store all error there:
root/logs/mod_mymodule.errors.php
You can of course change mod_mymodule to whatever you wish.
Hope this helps

If I understand your question right you can use JError class to get this done. You can raise error and handle them.

Related

error handling in codeigniter

In my project to catch all the PHP errors I have set up my error handling mechanism as follows:
I have set error_reporting() in index.php file which overrides
anything in the php.ini file
An error handler is set in system/codeigniter/CodeIgniter.php using
set_error_handler - this error handler, _exception_handler, is
found in system/codeigniter/Common.php
The _exception_handler function ignores E_STRICT errors, calls the
show_php_error function From the Exceptions system library if the
severity is that specified by your error_reporting() function in
index.php and logs the error according to whatever you have set up in your config.php file
The handler returns FALSE so after this PHP goes on to handle the
error however it normally would according your error_reporting level
and display_errors setting.
The thing that is puzzling me is that E_ERROR errors i.e. fatal errors don’t seem to be being caught by _exception_handler at all. It’s not just that show_php_error isn’t being called, it looks like the function just isn’t being called for them. This is obviously a problem as it means that they aren’t get handled by show_php_error or logged. For example if I deliberately mistype $this->load->views('foo'); in a controller, the handler doesn’t get called.
Any suggestion about error handling would be much appreciated, thanks!
Now this is a rather big debate:
Whether you should catch the fatal errors or not.
Some say that they are FATAL so you dont know in which condition is the system but I will go with the "try to do the cleanup if the error occured".
In order to catch ALL fatal errors you will need to setup a pre_system hook.
go to application/config/hooks.php and enter
$hook['pre_system'][] = array(
'class' => 'PHPFatalError',
'function' => 'setHandler',
'filename' => 'PHPFatalError.php',
'filepath' => 'hooks'
);
after that go to hooks directory and add your handling of the error:
<?php
class PHPFatalError {
public function setHandler() {
register_shutdown_function('handleShutdown');
}
}
function handleShutdown() {
if (($error = error_get_last())) {
ob_start();
echo "<pre>";
var_dump($error);
echo "</pre>";
$message = ob_get_clean();
sendEmail($message);
ob_start();
echo '{"status":"error","message":"Internal application error!"}';
ob_flush();
exit();
}
}
as you can see we are using the register_shutdown_function to run a function that checks if an error had occured and if it had send it via email to the developer.
This setup is working flawlessly for over 2 years in several CI projects that I have been working with.
I've found this answer under an other question (https://stackoverflow.com/a/3675357), and i think it is also useful for anyone reading this question.
"For codeigniter specific error handling, you can override its 'Exception' library class by creating My_Exception class in your application/libraries folder. Copy original library function signatures into it and put in your code. It will surely work."
Simply you can handle all type of error in one file which is display
your client because of php error or any other error is not good to
display client.
Simply place file Common_Exceptions.php in core folder . Common is my because in config file I have declare $config['subclass_prefix'] = 'Common_';
Copy system\core\Exceptions.php file and paste in core\Common_Excepions file (class Common_Exceptions extends CI_Exceptions) and do your change in this file and call view for your want and display to client when error come.
NOTE: $config['log_threshold'] = 1; enable in config file for errorlog write and after you see what error come.
One more suggestion on view file which is display when error is come there place time so when you see in log then match this time and find which error is come that time

Logging all the errors,warning and notices in PHP Automatically

I am looking for a way in which all the errors will be logged automatically with one line of code. If you know Asp.NET, you probably know what I mean like using Application_Error event handler.
I checked PHP Logging framework? question in SO but they all look same, you should log each and every log message manually which means I need to call the log function everywhere I want to log.
What I am looking for not something like this (which is used by KLogger)
require_once 'KLogger.php';
...
$log = new KLogger ( "log.txt" , KLogger::DEBUG );
// Do database work that throws an exception
$log->LogError("An exception was thrown in ThisFunction()");
// Print out some information
$log->LogInfo("Internal Query Time: $time_ms milliseconds");
// Print out the value of some variables
$log->LogDebug("User Count: $User_Count");
You can create your own custom error handler function in PHP and set it as the error handler
something like:
function handle_error($error_level,$error_message)
{
/*
here do what you want...typically log it into db/file/send out
emails based on error level etc..
*/
}
and to set this function as your default error handler for PHP add this line:
set_error_handler("handle_error");
All errors will now be handled by PHP based on what is written inside handle_error

Exception is not logged automatically when custom exception handler (set_exception_handler) is used

I want to use a custom exception handler (set with set_exception_handler() function) to control what is printed to a user when unhandled exception occurs.
Unfortunately, in this case exception is not logged to a php error log and I don't want to write my own logging code because automatic exception logging was absolutely ok for me.
The question is:
Is there a way to make PHP log exception (as by default) if custom exception handler was executed? If no, is there a way to log into main php error log file?
Is there a way to make PHP log exception (as by default) if custom exception handler was executed?
No, not from what PHP offers (e.g. return FALSE in the callback).
If no, is there a way to log into main php error log file?
Yes, you can use the error_logDocs function for that. The ExceptionDocs should contain the message as well as code, file name and line number.
It also is stringable and error_log() adds the delimiting newline character, so it directly works in logging (it will even downsize based on log_errors_max_len configured size):
set_exception_handler(function ($throwable) {
error_log((string)$throwable);
});
Or less verbose:
set_exception_handler('error_log');
Demo/Playground: https://3v4l.org/s41Vn
Another more or less dirty trick is to create an exception capturing object that remains in memory all the time. If it captures an uncatched exception, it will handle it and store it. In case of destruction (at the end of the process) it can re-throw it. Then PHP needs to deal with it and probably logs it. However I would consider that experimental and also perhaps short-sighted as there can be only one exception handler and it catches uncaught ones, so there is not much way to continue (more shutdown function material perhaps).

Best possible PHP error class

I am looking for some coding ideas on the following task I am trying to achive.
I have a list of Error Numbers, Description, and User Friendly Description in a document.
Ex:
Error Number, Description, User Friendly Description
-----------------------------------------------------
1, Internal Error, "An Internal Error has occurred. Please try again later".
2, Delete Failed, "Unable to delete an Entry. Please try later".
I want to write a PHP class to store all the above in such a fashion that I can access them later with ease when an error occurs in the code..
Ex: If my code received an error 2, I want to check that error code with the list of error codes in the class, retrieve the description, user friendly description and display it to the user.
I want this to be of minimum overhead. So, don't want to store it in database.
I am using PHP5 with Zend MVC framework. Anybody can help me with the best possible sample code?
Thanks
Write an ini file with the error code and the user friendly text.
write an class which extends Exception which fetches your errorcodes from the ini file. add a method e.g.
public function getUserFriendlyMsg(){}
which returns the string from the ini file.
in your normal code when you have such an error you just need to throw the exception. e.g.
throw new My_Exception('Delete failed',2);
in your e.g. controller:
try{
// your code
}catch(My_Exception $e){
echo $e->getUserFriendlyMsg();
}
Note: you should consider extending your excpetion class to log the failures to a logfile, for this you can introduce servity levels. (see the manual - exception handling)
I like to use a simple custom error handler and custom exception handler that do the following:
If in development mode:
Show the detailed error message
If E_WARNING or worse, output error message into a log file (e.g. using Zend_Log)
If a fatal error, halt execution and show a nice error page with a full backtrace
If in production mode:
Only log error messages
On fatal errors, halt execution and show a nice "an error has occurred" page only.
I like working with errors, so any exception I catch I call a trigger_error() for to do the output and logging.
You can also extend the default Exception class to do the logging and display. You would want to turn any error that occurs into exceptions. Manual errors you would then trigger as exception using throw.
Inspiration:
Kohana's Error Handler (Screenshot here) is the nicest and greatest I've seen to date. It's open source, maybe you can even grab out that part (make sure you read the license first, though.)

Centralized error reporting in PHP

is there a way to handle error reporting in a centralized manner in PHP? I'd like to be notified of all errors raised by my application by email.
What's the best way to achieve this for a whole application?
Thanks
You can use set_error_handler to handle errors at runtime any way you like.
As Kalium mentioned, you'll want to be using set_error_handler, but that only gets you part of the way. You also want to trap uncaught exceptions. For that, use set_exception_handler.
What I do myself is have my code trap errors, and convert those errors to approprate exceptions that I can catch elsewhere. For anything that isn't caught, I use the default exception handler to log and report them, and to display an appropriate error if necessary.
There are 3 types of errors:
System errors, such as warnings or fatal errors raised by PHP. 404 errors are also in this category.
Database errors by a malformed or failed query or database connection.
Logical errors such as when something went wrong in the internal working of your application not related to a server or database. For example if you expected a certain file to be in a given folder, but it wasn't.
The best way to create an ErrorHandler class that handles all three types of errors. For system errors, you would use set_error_handler or read up on one of the online tutorials such as this one.
For database, I suggest using a centralized Database class which handles all the queries. Use something like this:
$result=mysql_query($sql);
if (! $result)
{
$ErrorHandler->dbError(mysql_error(), $sql);
}
For logical errors, such as the error of not finding an expected file or database record, you would call up the same ErrorHandler class and do something like:
if ($logicalError)
{
$ErrorHandler->appError('Something bad happened',__LINE__, __FILE__);
$ErrorHandler->showAppErrorPage();
}
Here the __FILE__ and __LINE__ constants will give exactly the location where this error occurred. Read up on them on the php.net site.
Your ErrorHandler class can log all errors to a log file, email you, or even SMS/Text you on your mobile. It could also be used to redirect the user to an error page.

Categories