Laravel email notification upon all exceptions - php

I am developing a project and i would like to have a notification system especially for the "first days of live" - to receive an email everytime an exception is thrown .
I've read that article and implemented what it says. My problem is that the function report() in App\Exception\Handler.php doesn't trigger if an exception is thrown in one of my Controllers.
My problem :
I have an AdminController and a function which inserts some data in Database. The queries are inside a try/catch :
try {
// commands
} catch (\Exception $e){
Log::channel('admin_submissions')->info("Could not save submission. " . $e->getMessage());
return Redirect::back()->withErrors(['Could not save submission. Try again!']);
}
For testing purposes i've inserted inside the try{} an error to be thrown like :
try {
$error = \Illuminate\Validation\ValidationException::withMessages([
'field_name_1' => ['Validation Message #1'],
'field_name_2' => ['Validation Message #2'],
]);
throw $error;
// commands
But the dd("trigger") function (look below) is not triggered.
How could i make it so on every exception (everywhere) an email will be sent?
App\Exceptions\Handler.php
I have modified the report function just to check if the exception actually goes through that function :
public function report(Exception $exception)
{
dd("trigger");
if ($this->shouldReport($exception)) {
app('sneaker')->captureException($exception);
}
parent::report($exception);
}

You must firstly know which kind of exception your application thrown, may be the Exception that is thrown are in the $dontReport if so, you must firstly remove all exception from that table on you will get report for that Exception

Related

(Cake)PHP Error Thrown in Nested Function Doesn't Get Back to Initial Function

This isn't necessarily a CakePHP problem but I'm using CakePHP 2.8 and PHP 5.6.
I have a function named save_order which calls another function named changePathItemOrder using a try/catch. That function calls another function named _reorderItemsOnPath, which in turn calls another function named _moveItemsForwards. It's a few levels deep, so here's a little graphic to keep us all on track:
Cascade of Functions
The try/catch in sort_order is:
$data['status'] = 'success';
try {
$this->PathRepository->deletePathItemFromPath($milestoneId, $pathId, $accountId);
} catch(Exception $e) {
debug('Caught error');
$data['status'] = 'error';
$data['message'] = $e->getMessage();
}
$this->set(compact('data'));
$this->render('/Elements/json');
If an error occurs in _moveItemsForwards, I throw an error like:
throw new InternalErrorException('Invalid path item ID: ' . $pathItemId);
The problem is that the try/catch in sort_order doesn't catch the error thrown by _moveItemsForwards. The catch doesn't even execute because the debug doesn't show up in the resulting error message. I just get the following Error :-
500 Error! Something broke!
Return to the homepage
Invalid path item ID: 76
What's the best way to handle this error and get the error message back to the save_order function?

Cannot figure out catching thrown exception

I am trying to use a try/catch block to add in some error handling for a custom WordPress plugin that gets Tweets via the Twitter API.
For testing purposes, I am throwing an exception in my class construct method.
class Twitter_Settings() {
public function __construct() {
throw new \Exception('test');
}
}
then in my plugin file, I am doing:
function twitter_init_settings() {
try {
return new Twitter_Settings();
} catch ( Exception $e ) {
echo $e->getMessage();
}
}
twitter_init_settings();
On the frontend, where I am spitting out $tweets = twitter_feed()->output_feed(); (with a foreach loop afterwards) I am getting an Uncaught Exception error. Oddly, it shows the custom message, 'test', so it must know about my exception, so why is it saying it is uncaught?
Uncaught Exception error happen while an exception is not catched (in try catch statements)
Remove the return statment because the catch might not be reached.

Handling a non-fatal exception in Laravel

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.

I'm trying to handle an Exception in PHP but stack error is still showing rather than being handled by catch

I'm calling a method that I know could cause an error and I'm trying to handle the error by wrapping the code in a try/catch statement...
class TestController extends Zend_Controller_Action
{
public function init()
{
// Anything here happens BEFORE the View has rendered
}
public function indexAction()
{
// Anything `echo`ed here is added to the end of the View
$model = new Application_Model_Testing('Mark', 31);
$this->view->sentence = $model->test();
$this->loadDataWhichCouldCauseError();
$this->loadView($model); // this method 'forwards' the Action onto another Controller
}
private function loadDataWhichCouldCauseError()
{
try {
$test = new Application_Model_NonExistent();
} catch (Exception $e) {
echo 'Handle the error';
}
}
private function loadView($model)
{
// Let's pretend we have loads of Models that require different Views
switch (get_class($model)) {
case 'Application_Model_Testing':
// Controller's have a `_forward` method to pass the Action onto another Controller
// The following line forwards to an `indexAction` within the `BlahController`
// It also passes some data onto the `BlahController`
$this->_forward('index', 'blah', null, array('data' => 'some data'));
break;
}
}
}
...but the problem I have is that the error isn't being handled. When viewing the application I get the following error...
( ! ) Fatal error: Class 'Application_Model_NonExistent' not found in /Library/WebServer/Documents/ZendTest/application/controllers/TestController.php on line 23
Can any one explain why this is happening and how I can get it to work?
Thanks
use
if (class_exists('Application_Model_NonExistent')) {
$test = new Application_Model_NonExistent;
} else {
echo 'class not found.';
}
like #prodigitalson said you can't catch that fatal error.
An error and an exception are not the same thing. Exceptions are thrown and meant to be caught, where errors are generally unrecoverable and triggered with http://www.php.net/manual/en/function.trigger-error.php
PHP: exceptions vs errors?
Can I try/catch a warning?
If you need to do some cleanup because of an error, you can use http://www.php.net/manual/en/function.set-error-handler.php
Thats not an exception, thats a FATAL error meaning you cant catch it like that. By definition a FATAL should not be recoverable.
Exception and Error are different things. There is an Exception class, which you are using and that $e is it's object.
You want to handle errors, check error handling in php-zend framework. But here, this is a Fatal error, you must rectify it, can not be handled.

CakeEmail how to determine failure before stack trace?

I am trying to catch when an email fails so that I can save the required data in my database and I can attempt to send at a later date.
I thought the following should work as it does when using save()
if ( $email->send() ) {
//..success - works..
} else {
//..fail - never gets here, stack trace
}
obviously you are not in debug mode there.
if you were, you would see that this actually throws an exception.
and you are catching sth there, just not the exception thrown :)
try this:
try {
$success = $email->send();
...
} catch (SocketException $e) { // Exception would be too generic, so use SocketException here
$errorMessage = $e->getMessage();
...
}
this way you can catch the exception and do sth here.

Categories