In my laravel app, say I have a bit of code as follows, as an example
function convert_amount($amount, $currency, $date)
{
if (strlen($currency) <> 3)
{
// Exception thrown
} else {
// convert $amount from $currency on $date
}
return $amount;
}
Here, I am simply converting a number from a currency to base. I perform a simple check to see if the currency string passed is 3 character to ensure it's a ISO currency code (EUR, GBP, USD etc). If not I want to throw an exception but not result in the app falling to an error page like is often the case with Laravel's error handler.
Instead, I'd like to continue processing the page but log the exception and perhaps display an error in a flash message. Is there a listener I can define for Laravel that achieves this? Do I need to define a new exception type NonFatelException
perhaps that does the logic.
Edit
Essentially, I guess I could register a new exception handler like so:
class NonFatalException extends Exception {}
App::error(function(NonFatalException $e)
{
// Log the exception
Log::error($e);
// Push it into a debug warning in the session that can be displayed in the view
Session::push('debug_warnings', $e->getMessage());
});
Then somewhere in my app:
throw new NonFatalException('Currency is the wrong format. The amount was not converted');
The trouble with this is that the default exception handlers will then be called resulting in an error page rather than the page that was going to be reached. I could return a value in my handler to avoid the default but I believe that would result in that return value alone being shown and the rest of my scripts would not be run.
You are on a right path. Why not use try...catch
tho?
Your helper method will be:
function convert_amount($amount, $currency, $date)
{
if (strlen($currency) <> 3)
{
throw new NonFatalException('Currency is the wrong format. The amount was not converted');
} else {
// convert $amount from $currency on $date
}
return $amount;
}
And whenever you'll use it, put it in a try...catch
:
try {
convert_amount($amount, $currency, $date);
} catch (NonFatalException $e) {
// Log the exception
Log::error($e);
// Push it into a debug warning in the session that can be displayed in the view
Session::push('debug_warnings', $e->getMessage());
}
This way, your app will never stopp and you have the error message in Session.