synkyo
synkyo

Reputation: 440

Stop laravel from including a trace within an exception

I have my own exception extension that when called I want it to output a message to the browser. However, when I throw this exception, catch it and output the message but the message is a trace.

Here is my global.php:

class ApiException extends Exception {}
App::error(function(ApiException $ex){
    dd($ex->getMessage());  
});

My code snippet:

try {
    if (!Input::get('password')) {
        throw new Exception('Password not set');
    }
    if (User::all()->count()) {
        throw new Exception('User already exists');
    }
    Artisan::call('db:seed', [
        '--class' => 'VerifyUserSeeder'
    ]);
    $User = \Toddish\Verify\Models\User::find(1);
    $User->password = Input::get('password');
    $User->save();
} catch (Exception $ex) {
    throw new ApiException($ex);
}

Output to browser:

exception 'Exception' with message 'Password not set' in /Users/kevin/Documents/Web/app/controllers/Settings/SetupController.php:8 Stack trace: #0 [internal function]: SetupController->setupPassword() 1 /Users/kevin/Documents/Web/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(231): call_user_func_array(Array, Array) #2 .......

Upvotes: 3

Views: 1172

Answers (2)

synkyo
synkyo

Reputation: 440

After re-arranging the nesting of the try catch and throwing ApiException directly as Fabio questioned and suggested, this solved the problem. My code is now as follows:

if (!Input::get('password')) {
    throw new ApiException('Password not set');
}
if (User::all()->count()) {
    throw new ApiException('User already exists');
}
try {
    Artisan::call('db:seed', [
        '--class' => 'VerifyUserSeeder'
    ]);
    $User = \Toddish\Verify\Models\User::find(1);
    $User->password = Input::get('password');
    $User->save();
} catch (Exception $ex) {
    throw new ApiException($ex);
}

Upvotes: 0

Fabio Antunes
Fabio Antunes

Reputation: 22862

Can you explain why you are throwing general exceptions, catch them and then throw a new exception again?

Why don't you just throw an ApiException directly?

if (!Input::get('password')) {
    throw new ApiException('Password not set');
}
if (User::all()->count()) {
    throw new ApiException('User already exists');
}
Artisan::call('db:seed', [
    '--class' => 'VerifyUserSeeder'
]);
$User = \Toddish\Verify\Models\User::find(1);
$User->password = Input::get('password');
$User->save();

Upvotes: 1

Related Questions