我有自己的异常扩展,在调用时我想让它向浏览器输出一条消息。但是,当我抛出此异常时,捕获它并输出消息,但消息是跟踪。
这是我的global.php:
class ApiException extends Exception {}
App::error(function(ApiException $ex){
dd($ex->getMessage());
});
我的代码段:
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);
}
输出到浏览器:
异常'异常',其中包含“未设置密码”消息 /Users/kevin/Documents/Web/app/controllers/Settings/SetupController.php:8 堆栈跟踪:#0 [内部功能]:SetupController-> setupPassword() 1 /Users/kevin/Documents/Web/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(231): call_user_func_array(Array,Array)#2 .......
答案 0 :(得分:1)
你能解释为什么抛出一般异常,捕获它们然后再次抛出新异常吗?
为什么不直接抛出ApiException?
{{1}}
答案 1 :(得分:0)
在重新安排try catch的嵌套并直接抛出ApiException后,Fabio质疑并建议,这解决了这个问题。我的代码现在如下:
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);
}