PHP Global Exception handling across all classes - php

In PHP,is there any way to handle exceptions globally using one method? If there is, how could I do that?
I want to use the method which handles exception across all classes.
The reason that I want to achieve this is I do not want to repeat same code all the time.
Here is the example of the exception handling.
try {
***SOME CODE TO EXCUTE***
}
catch ( Exception $e ) {
/* custom function to handle exception */
$msg = exceptionHandler($e);
$this->error(0,500, $e->getMessage());
}

Related

Symfony 4 custom exception handler for certain controllers

From my understanding there can only be one exception handler which will catch all unhandled exceptions. However, is there an elegant way to have a specific exception handler for Controllers A and B, and controllers C, D, etc. would be handled by default exception handler?
I don't think this is possible by default, other than creating a kernel eventlistener. However, you can create something simple yourself.
In a Controller Method, you might could do something like
public function index()
{
try {
// Do normal logic here.
} catch (\Exception $e) {
// Do whatever you want with any exception.
// Or Call your exception handler: MyExceptionHandler::handle()
}
}
You can also create a custom AbstractController so it might be a bit simpler. In which you extend the render function, so you abstract that logic away

Handle specific Exceptions in php

I want to catch a specific Exception and handle it properly. However, I have not done this before and I want to do it in the best way.
Will it be correct to create a separate class something like
class HandleException extends Exception
{
//my code to handle exceptions;
}
and in it have different methods handling the different exception cases? As far as I understand, the Exception class is like an "integrated" class in php so it can be extended and if an Exception is caught it is not obligatory to terminate the flow of the program?
And, an instance of this class will be created when an exception is caught? Sth. like
catch ( \Exception $e ) {
$error = new HandleException;
}
You CAN extend the basic Exception object with your own, to provide your own exception types, e.g.
class FooExcept extends Exception { .... }
class BarExcept extends Exception { .... }
try {
if ($something) {
throw new FooExcept('Foo happened');
} else if ($somethingelse) {
throw new BarExcept('Bar happened');
}
} catch (FooExcept $e) {
.. foo happened, fix it...
} catch (BarExcept $e) {
... bar happened, fix it ...
}
If an Exception is caught, then the program DOESN'T necessarily have to abort. That'd be up to the exception handler itself. But if an exception bubbles always back up to the top of the call stack and ISN'T caught, then the entire script will abort with an unhandled exception error.
From the manual
Multiple catch blocks can be used to catch different classes of
exceptions. Normal execution (when no exception is thrown within the
try block) will continue after that last catch block defined in
sequence. Exceptions can be thrown (or re-thrown) within a catch
block.
So you can do something like this:
try {
// some code
} catch ( HandleException $e ) {
// handle sthis error
} catch ( \Exception $e ) {
// handle that error
}
This will handle different exceptions. You can also use the finally keyword with newer versions of PHP.

Laravel 5 controller exception handler

I have an application in which my controllers are broken up into specific groups (API, CMS and front-end), this is already set up using Router groups. My question is how would one go about creating custom error handling for each group.
For example, when an exception occurs in any API controller action I would like to send back json with an error code and message, an exception in the CMS would output a detailed error page, and an exception on the front end would send the user to a generic 404 or 500 error page (as appropriate).
I am aware of how I could do this manually in each controller action, but that might get very repetitive. Ideally, I would want to create one handler for each and automatically use it across the board.
I am also aware of the App\Exceptions\Handler class, but if any of the controller groups could return a ModelNotFoundException, for example, how do I differentiate where the exception came from?
Is there another place that this type of exception handler could be inserted?
If you go to app\Exceptions\Handler.php file (which you mentioned) you can do it what you want.
You could for example define your render function this way:
public function render($request, Exception $e)
{
$trace = $e->getTraceAsString();
if ($e instanceof ModelNotFoundException
&& mb_strpos($trace, 'app\Http\Controllers\WelcomeController')
) {
return response()->json('Exception ' . $e->getMessage());
} elseif ($e instanceof ModelNotFoundException) {
return "General model not found";
}
return parent::render($request, $e);
}
and add to imports use Illuminate\Database\Eloquent\ModelNotFoundException;
and now if you throw ModelNotFoundException in your WelcomeController or you for example run another class' method from your WelcomeController and this method will throw ModelNotFoundException you can track it and return json response. In other cases if exception will be instance of ModelNotFoundException you can render your exception in other way and in all other cases you can use standard exception method to render.
This way you don't need to define anything in your controller, you can do it just in Handler and it it's more complicated you could create separate methods or create new classes to handle specific exceptions in the way you want and run them in this handler.

What is the point of using custom exception class in php?

In some libraries it is common practice to make custom Exception classes for every error condition, like:
class FileNotFound_Exception extends Exception {}
You can handle certain type of Exception, however you cannot read all source code of all libraries to remember each Exception class, and cannot take full advantage of using custom Exceptions. Most of time I just catching them with base Exception class:
catch (Exception $e)
{
// log and display friendly error
}
Is there other ways to have benefit of custom Exception classes, without writing long list of catch blocks?
I like Exceptions, but don't know how to use them properly. Thank you.
The benefit of having your own Exception class is that you, as the author of the library, can catch it and handle it.
try {
if(somethingBadHappens) {
throw MyCustomException('msg',0)
}
} catch (MyCustomException $e) {
if(IcanHandleIt) {
handleMyCustomException($e);
} else {
//InvalidArgumentException is used here as an example of 'common' exception
throw new InvalidArgumentException('I couldnt handle this!',1,$e);
}
}
Well, custom exception classes lets you route your errors properly for better handling.
if you have a class
class Known_Exception extends Exception {}
and a try catch block like this:
try {
// something known to break
} catch (Known_Exception $e) {
// handle known exception
} catch (Exception $e) {
// Handle unknown exception
}
Then you know that Exception $e is an unknown error situation and can handle that accordingly, and that is pretty useful to me.

php symfony exception handling/error handling

Working on a symfony application that uses nusoap (is this the best method for integrating soap work with php/symfony?) for taking credit card payments.
I've simplified an example of my code below.
What I'm struggling with is the best way to handle exceptions. The example below only has 1 custom exception (where should my custom exceptions reside within the directory structure of symfony? (lib/exception?)) But what happens when there are several different types of exceptions that handle a specific error? It's not very elegant to have a try/catch block with 20 odd exceptions.
I'm also not sure of where I should be throwing and catching. I need to set some user flashes to alert the user of any problems, so I figure the catching should be done in the actions controller rather than within the class that handles the soap call.
Could anyone please advise where I might be going wrong?
I hate messy code/solutions and want to stick to the DRY principle as much as possible. I think I might also be missing some built in symfony functionality that might help with this but whenever I search I usually find examples that are for symfony 1.2, I'm using 1.4.
Some examples would be great, thanks.
lib/soap_payment.class.php
class SoapPayment
{
public function charge()
{
/*assume options are setup correctly for sake of example*/
try
{
$this->call();
}
catch (SoapPaymentClientFaultException $e)
{
/* should this be caught here? */
}
}
private function call()
{
$this->client->call($this->options);
if ($this->client->hasFault())
{
throw new SoapPaymentClientFaultException();
}
}
}
apps/frontend/payment/actions/actions.class.php
class paymentActions extends sfActions
{
public function executeCreate(sfWebRequest $request)
{
/* check form is valid etc */
$soap_payment = new SoapPayment();
try
{
$soap_payment->charge();
}
catch (SoapPaymentClientFaultException $e)
{
/* or throw/catch here? */
$this->getUser()->setFlash('error', ...);
$this->getLogger()->err(...);
}
/* save form regardless, will set a flag to check if successful or not in try/catch block */
}
}
One not very well known feature of Symfony is that exceptions can manage the content sent in a response. So you could do something like this:
class SoapException extends sfException
{
public function printStackTrace() //called by sfFrontWebController when an sfException is thrown
{
$response = sfContext::getInstance()->getResponse();
if (null === $response)
{
$response = new sfWebResponse(sfContext::getInstance()->getEventDispatcher());
sfContext::getInstance()->setResponse($response);
}
$response->setStatusCode(5xx);
$response->setContent('oh noes'); //probably you want a whole template here that prints the message that was a part of the SoapException
}
}
If you need a cleaner handling of SOAP exceptions, like setting flashes, etc. you'll probably have to catch each exception. One idea here might be to create a generic SoapException class that is extended by more specific SoapExceptions so you don't have to catch a bunch of different types. The above code may be a useful fallback mechanism as well.
Finally, yes, you should place custom exceptions in lib/exception.

Categories