やったこと

webサービスを作るときに考えたことを垂れ流します

【CakePHP3】例外処理 Exception() が使えないとき!

CakePHP3で例外を発生させたいのですが「Exception()」を使おうとすると「Error: Class 'App\Controller\Exception' not found 」とエラーが表示されて使用出来ません。

「Exception()」を使うには、下記のように「use \Exception;」しないとダメなんですね~。

use \Exception;

public function rename(){
  try{
    $user = $this->Users->find()->where(['name' => 'hogetan'])->first();
    $user->name = 'fugatan';
    $ret = $this->Users->save($user);
    if (!$ret){
      throw new Exception();
    }
  } catch (Exception $ex) {
    $this->log("エラー!", "debug");
  }
}


ちなみにCakePHP3には、デフォルトでいろんな例外が用意されています。例えば「404NotFound」の例外とかは、以下のようにして発生できます。

use Cake\Network\Exception\NotFoundException;

   public function test()
    {
      //・・・
      throw new NotFoundException();
      //・・・
    }

自分で変な例外を投げるよりも、デフォルトで用意されてるものを使った方がいいかもしれませんね・・。

以上!