LoginSignup
20
16

More than 5 years have passed since last update.

Laravel系 HttpExceptionの取り扱いまとめ

Posted at

Lumenでの取り扱いを中心に。

HttpExceptionとは

HttpのException

  • Model層とかで使わない方が良いよ
  • Exception自体がView(Response)に関する情報持ってる気持ち悪いやつ
  • Handlerとかでまとめてキャッチするのには便利な奴

運用方法としては2種類に分かれると思う。

継承ツリーの中心としてのみ使うよ派

例外にResponseのプロパティとか持たせるのは気持ち悪いよ派

独自の例外型を色々作って例外->Responseの変換はhandler等で行う。

render可能な例外として使うよ派

throwするときにReponseに関するデータを色々Exceptionに詰め込む派

HttpException

定義はこんな感じになっている。

namespace Symfony\Component\HttpKernel\Exception;

/**
 * HttpException.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
class HttpException extends \RuntimeException implements HttpExceptionInterface
{
    private $statusCode;
    private $headers;

    public function __construct($statusCode, $message = null, \Exception $previous = null, array $headers = array(), $code = 0)
    {
        $this->statusCode = $statusCode;
        $this->headers = $headers;

        parent::__construct($message, $code, $previous);
    }

    public function getStatusCode()
    {
        return $this->statusCode;
    }

    public function getHeaders()
    {
        return $this->headers;
    }
}

コンストラクタの順番がアレなのはご愛嬌。

headerに関する情報とmessageを受け付ける事が出来るみたい。

ちなみに後ろ2つのメソドはHttpExceptionInterfaceの実装。

Exceptionの型としてはRuntimeException (実行時例外)となっている。

HttpExceptionの運用

laravel/lumen系の例外処理では、$dontReportの項目でその存在を確認することが出来る。

            protected $dontReport = [
                'Symfony\Component\HttpKernel\Exception\HttpException',
            ];

実際に何か処理を入れるならきっとrenderの方になるかと思う。

クラスの運用

HttpExceptionそれ自体はコンストラクタに必須パラメータがあったりと使いづらい。

Symfonyの中でも、HttpExceptionを直接newるというよりかは拡張型で第一引数を埋める、みたいなやり方が取られてるっぽい。

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Exception;

/**
 * AccessDeniedHttpException.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Christophe Coevoet <stof@notk.org>
 */
class AccessDeniedHttpException extends HttpException
{
    /**
     * Constructor.
     *
     * @param string     $message  The internal exception message
     * @param \Exception $previous The previous exception
     * @param int        $code     The internal exception code
     */
    public function __construct($message = null, \Exception $previous = null, $code = 0)
    {
        parent::__construct(403, $message, $previous, array(), $code);
    }
}

20
16
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
20
16