LoginSignup
7
5

More than 5 years have passed since last update.

PHPのExceptionで配列を扱えるようにする

Last updated at Posted at 2018-05-17

Exceptionで配列を扱いたい!

ダメなパターン

Exceptionに配列を入れると、パラメーターが間違ってるよとエラーを出す

エラーになる
throw new \Exception(array('配列','入れたい'), 1);

Error [ Error ]:
Wrong parameters for RuntimeException([string $message [, long $code [, Throwable $previous = NULL]]])

🎉解決策

ならExceptionを拡張して、独自の例外クラスを作れば解決しそう!
以下例外の拡張方法
json_encodeで配列をJson形式にして、配列を受け取るときにjson_decodeでJsonを配列に戻す。

Exeptionの拡張クラス
class OriginalException extends Exception {

  public function __construct($message = null, $code = 0, Exception $previous = null) {

    // 全てを正しく確実に代入する
    parent::__construct(json_encode($message), $code, $previous);
  }

  public function getArrayMessage($assoc = false) {
    return json_decode($this->getMessage(), $assoc);
  }
}
Exceptionの使用クラス
try {
   throw new OriginalException(array('エラー', 'です'));
} catch (OriginalException $e) {
   var_dump($e->getArrayMessage());
}

参考サイト

PHP マニュアル - 例外の拡張
stackoverflow

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5