سؤال

In this snippet the problem is that I'm saving $model which is null (thanks @Lucas Brito).
What I don't understand is:

  1. Why the exception isn't caught in the try/catch that is around $model->save()
  2. Why the $exception variable in the App::fatal is empty
  3. How could I show a more explicit error

Every time I call $model->save();

$new = new System();
$new->imcid = $imcid;
$new->name = $name;
$new->validate();
Log::info('At update');
try{
    $model->save();
}catch(\Exception $e){
    Log::info('Exception thrown');
}
Log::info('Done');

In the log I can see the 'At update' but not 'Exception thrown' or 'Done'.
I get the message defined on routes.php

App::fatal(function($exception){
    return Response::json(array(
        'message' => 'damn...',
        'exception' => $exception
    ), 500);
});
هل كانت مفيدة؟

المحلول 3

The Exceptions were escalating all the way to fatal because I missed the \ in Log.

So:

  1. It's the code inside the catch that is throwing the error that goes all the way to App:fatal

  2. I could not replicate this again but write the exception through:

    \Illuminate\Support\Facades\Log::error('message'.$exception);
    

    in App::fatal worked when I was debugging in different circumstances.

  3. With the above line in the App::fatal.

نصائح أخرى

I think you're trying to save the wrong variable. Shouldn't save $new?

Here's how I do:

$reg = new Area;

$reg->name          = $name;
$reg->created_at    = time();
$reg->created_by    = Auth::user()->id;

$reg->save();

Instead of following code:

try{
    $model->save();
}catch(\Exception $e){
    Log::info('Exception thrown');
}

Try this:

if(!$model->save()) {
    throw new Exception("Couldn't save!");
}
else {
    // success
}

By default there is (create if not) an exception handler in your app/start/global.php, like this:

App::error(function(Exception $exception, $code)
{
    Log::error($exception);
    //Log::error($exception->getMessage());
});

You may also create a custom exception class by extending the base Exception class and can throw that custom exception instead.

Update: You are saving $model->save(); instead of $new->save();.

Why didn't it got caught in my catch

It's because a fatal error has occurred and you have a registered handler for fatal errors like one given below and error caught by that handler instead:

App::fatal(function($exception){
    //...
    return Response::json(...);
});

So, once you send the response from any error handler then it stops propagating to up, just finished the propagating with response sent.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top