set_exception_handler for specific exceptions - php

I'm using a new API and I want to handle exceptions specific to it, and return the data from the exceptions to JS function that made a request. The thing is - I have a fatal_handler registered with register_shutdown_function in the program, and I want to avoid it for these exceptions, because It won't let me return the necessary data to the JS function, and I don't want to mess with this specific handler because it's more general.
I managed to override it with set_exception_handler, but I assume it will catch other unhandled exceptions as well.
Is there any way to define the instance of the exception (e.g AException) that will be handled in set_exception_handler(), same as in a catch block?
My only idea was to check the type of the exception object I'm getting to the handler function (with instanceof, and rethrow it if it's not the type I'm looking for.

Related

The proper way to do exception handling

Now what I generally do when writing code is something like this
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided');
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found');
}
}
in the laravel doc we see:
https://laravel.com/docs/5.4/errors
public function report(Exception $exception)
{
if ($exception instanceof CustomException) {
//
}
return parent::report($exception);
}
Now how to I properly handle the exception? they are all the same exception and they have no code neither. Should I provide an error code?
the problem with php exception is that they use integers. Is quite annoying imho. Better would be 'changeauthor_bookid_notfound' as code instead of a random number. Should I create an exception class for each single exception? e.g. not reuse MyAppException that seems a bit tedious. I would have a trillion classes.
Now if for a special exception I want special handling, with my code, I cannot easily do it. I have no code to check for (e.g. $exception->code == 3331 then do special) and I don't have custom exception classes neither
what is a proven good solid way to handle this case?
code, new class on each error, something else all together?
and if provide a code, what is a nice way to do it?
The "proper" way to do it would be to define either a custom Exception class for each exception, or to define custom exceptions based on the type of error being thrown, however realize that Laravel already has many built in exceptions and mechanics for handling the use cases you outlined.
For instance, in the case of the "Book Not Found" exception, rather than manually triggering an exception yourself, you could use Books::findOrFail($id); which throws an instance of ModelNotFoundException when appropriate.
Also, in PHP there is no need to handle exceptions for unprovided arguments. Unless expressly denoted as optional, all method arguments are required, and Laravel will throw a PHP exception if an argument is missing.
Additionally, Laravel provides the abort() magic method which throws a HTTP error along with a custom error message and can be used like so:
abort(418, "I'm a teapot...")
So, if you must reinvent the wheel, the proper way is to define custom exception classes and define the custom handlers for those classes, but realize that Laravel already has many built in tools for managing exceptions without needing to do so.

PHP, how to make a function catch, catch PDOExceptions

Can you have a method throw any exceptions that occurs within it's method body? I want to automatically 'throw' any PDO related exceptions without always having to use 'try/catch' blocks within a function/method.
Example:
function testExcption($a..) throws PDOException{
// PDO related code here.
}
So can I 'throw' and exception at the function/method declaration level and without any try/catch blocks?
EDIT
I'm trying to avoid always having to write 'try/catch' because I only care for the PDO related exceptions that can occur within those functions/methods. I have lots of methods/functions and I'm tired of using 'try/catch' all the time for PDO error handling, and again I only care for the PDO exceptions in those functions/methods. Does that make sense?
EDIT
Is there a way to get PDO errors w/o try/catch blocks?
Maybe you are mixing things. Throwing exceptions is done without any try/catch statment. Throwing Exceptions is as easy as:
function nonsensefunc(){
throw new Exception('<Description of Error>');
}
On the other side, when calling you function, you have to use try/catch, you are catching them.
So what happens, when you do not catch the errors? The Exception is thrown a level higher and finally is printed out. Mostly it triggers an abort in PHP and stops the rest of the script.
So what is your expected behaviour? The only way of doing other thing as the default behaviour (printing the error and stopping) is to catch it.

Monolog: how to catch all errors and exceptions

I'm missing something really obvious.
How can I make monolog record all php errors, php user errors, and exceptions?
Before using monolog, I wrote my own functions which I passed to set_error_handler(), register_shutdown_function() and set_exception_handler(). Is there a way of doing this using Monolog's API, or do I have to the following?
Write an error handler and exception handler which I pass to PHP's functions above
In those handlers, call the appropriate Monolog functions such as Logger::addError(...) using a switch statement or similar
Surely there must be a Monolog API that does the above in a single call?
From the ErrorHandler class docs:
use Monolog\ErrorHandler;
$logger = new Logger('Logger Name');
ErrorHandler::register($logger);
Old question but since it was not yet answered - ErrorHandler will do exactly what you're after.
From The documentation:
ErrorHandler: The Monolog\ErrorHandler class allows you to easily register a Logger instance as an exception handler, error handler or fatal error handler.

How does throw work?

I would like to know how throw works in PHP.
For example, does it act like a die() or exit()? How can I know what is done internally?
I am asking this because I saw Kohana using their $this->redirect() method with a throw to terminate the script execution instead of the traditional exit.
throw is not like exit or die at all. Throwing an exception does not automatically terminate the application, a thrown exception can be caught by the application. Only when an exception is not caught will the application be terminated.
try {
throw new Exception;
} catch (Exception $e) {
echo 'caught it';
}
echo 'not dead yet';
Exceptions are a mechanism to signal errors to higher up callers in a more flexible and rigorous manner than simple return false statements would allow. They are not comparable to a simple exit or die.
I don't know what Kohana does exactly, but throwing an exception instead of using a simple exit or die is an abuse of exceptions. Exceptions should be thrown in exceptional error circumstances only.
As already explained, you use throw to throw exceptions that can be caught "further up" in your application.
When you work with objects and object oriented programming you start coding every single object you make as a standalone object that you can give to someone else. The public methods of these are an API, and the phpdoc above each public method details what exceptions the class might throw under certain circumstances.
So, someone has created a standalone object that does something for you, like writing to a disk. You want to use this object, so you look at the docs and see it throws a PermissionsException when the object can't write to the disk because of a permissions issue.
In your code that uses this person's object, you now know that you should catch that exception, log it, and continue however you want your application to work given that circumstance (show a nice error to the user if it's via an AJAX call, for example).
So, knowing this, when you code your own objects, make descriptive exceptions for different circumstances that someone who you give your object to can use and respond to in their own applications.
Both die and exit you don't really want to use in production applications. They're useful for debugging when you do a var_dump() and then want to halt application execution straight afterwards or if you want to completely stop the script from running for some reason.
As for why your specific found piece of code does it this way, you should ask the developer if it isn't documented with good reasoning.
Using "throw" without try/catch will terminate the script with a "catchable fatal error". As far as I know there's no benefit in using "throw" this way. If you want to terminate a script you should use exit(), so you don't need to suppress the error message.

Has trigger_error() in PHP been deprecated for something better in PHP5?

I used to use this when I wanted to trigger errors in PHP, coming from a PHP4 background. Note I had my own set_error_handler() for handling these errors.
if ($error) {
trigger_error('Sorry, error has occured');
}
I can't remember where, but sometime ago someone told me I should be 'using exceptions'. As I'm re factoring a lot of my old code, I figured now is the time to get some good advice on my error handling implementation.
Now that I'm using PHP5 (and a bit smarter than I was when I wrote the older code), is my trigger_error() just an old way of doing things, and if so, what is the best way to handle errors in PHP5?
Yes, you may want to start looking into the PHP 5 exception model. Remember though that just because something is new doesn't mean that you must adopt it. Only adopt those features that you need and make sense in your domain.
That being said, I feel that exceptions are a good concept to grasp and even if you decide not to adopt them you will be all the better for the experience.
I would like to suggest that you read PHP: Exceptions - Manual:
PHP 5 has an exception model similar
to that of other programming
languages. An exception can be thrown,
and caught ("catched") within PHP.
Code may be surrounded in a try block,
to facilitate the catching of
potential exceptions. Each try must
have at least one corresponding catch
block. Multiple catch blocks can be
used to catch different classes of
exeptions. Normal execution (when no
exception is thrown within the try
block, or when a catch matching the
thrown exception's class is not
present) will continue after that last
catch block defined in sequence.
Exceptions can be thrown (or
re-thrown) within a catch block.
I would also encourage you to read What Is an Exception? (Note this is a Java tutorial but the concepts are universal)
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Edit: In order to implement a global exception handler (basically in order to establish a default exception handler that will handle previously unhandled exceptions) you will want to us the set_exception_handler function.
Using exceptions is the object-oriented way to trigger and handle your own application errors.
The PHP manual topic on exceptions is probably a good place to start.
Here is a small example:
function doSomething() {
if ($error) {
throw new Exception('Some descriptive error message.');
}
}
try {
doSomething();
}
catch (Exception $e) {
die('<p class="error">' . $e->getMessage() . '</p>');
}

Categories