Laravel 라우팅 예외처리

1 개념[ | ]

  • 라라벨에서 routes.php 파일에 정의하지 않은 경로를 접근할 경우 지정된 곳으로 리다이렉트되게 하는 방법
app\Exceptions\Handler.php 파일의 Handler class의 render 메소드에 조건을 추가
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if($this->isHttpException($e))
        {
            switch ($e->getStatusCode()) 
            {
                // 404 not found
                case 404:
                    return redirect()->guest('post');
                    break;

                // 500 internal error
                case '500':
                    return redirect()->guest('post');
                    break;

                default:
                    return $this->renderHttpException($e);
                    break;
            }
        }
        else
        {        
            return parent::render($request, $e);
        }
    }
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}