IT TIP

Laravel 5에서 예외 / 누락 된 페이지를 어떻게 잡나요?

itqueen 2020. 12. 7. 21:24
반응형

Laravel 5에서 예외 / 누락 된 페이지를 어떻게 잡나요?


Laravel 5 년, App::missing그리고 App::error, 그래서 방법 캐치 예외없는 페이지는 현재 사용할 수 없습니다 할 수 있습니까?

문서에서 이에 관한 정보를 찾을 수 없습니다.


Laravel 5에서는 .NET의 render메서드를 편집하여 예외를 포착 할 수 있습니다 app/Exceptions/Handler.php.

누락 된 페이지 (라고도 함 NotFoundException) 를 포착 하려면 예외 $e가의 인스턴스 인지 확인해야합니다 Symfony\Component\HttpKernel\Exception\NotFoundHttpException.

public function render($request, Exception $e) {
    if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
        return response(view('error.404'), 404);

    return parent::render($request, $e);
}

위의 코드를 사용하여 $einstanceofof 인지 확인 하고 HTTP 상태 코드 404의 콘텐츠로 보기 파일 과 함께를 Symfony\Component\HttpKernel\Exception\NotFoundHttpException보냅니다 .responseerror.404

이것은 모든 예외에 사용할 수 있습니다. 따라서 앱에서의 예외를 보내는 App\Exceptions\MyOwnException경우 대신 해당 인스턴스를 확인합니다.

public function render($request, Exception $e) {
    if ($e instanceof \App\Exceptions\MyOwnException)
        return ''; // Do something if this exception is thrown here.

    if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
        return response(view('error.404'), 404);

    return parent::render($request, $e);
}

오늘부터 커밋 (9db97c3)하면 / resources / views / errors / 폴더에 404.blade.php 파일을 추가하기 만하면 자동으로 찾아서 표시합니다.


커밋 이후 30681dc9acf685missing() 방법은 이동했다 Illuminate\Exception\Handler클래스입니다.

따라서 얼마 동안 이렇게 할 수 있습니다.

app('exception')->missing(function($exception)
{
    return Response::view('errors.missing', [], 404);
});


... 그러나 최근에는 62ae860 에서 리팩토링이 수행되었습니다 .

이제 다음을 추가 할 수 있습니다 app/Http/Kernel.php.

// add this...
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Response;

class Kernel extends HttpKernel {

    (...)

    public function handle($request)
    {
        try
        {
            return parent::handle($request);
        }

        // ... and this:
        catch (NotFoundHttpException $e)
        {
            return Response::view('errors.missing', [], 404);
        }

        catch (Exception $e)
        {
            throw $e;
        }
    }


마지막으로, Laravel은 아직 많은 개발 중이며 변경 사항이 다시 발생할 수 있습니다.


Angular HTML5 mode could cause a bunch of missing pages (user bookmark few page and try to reload). If you can't override server settings to handle that, you might thinking of override missing page behaviour.

You can modify \App\Exceptions\Handler render method to push content with 200 rather than push 404 template with 404 code.

/**
 * 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) && $e->getStatusCode() == 404)
    {
        return response()->view('angular', []);
    }
    return parent::render($request, $e);
}

In case you want to keep the handler in your web routes file, after your existing routes:

Route::any( '{all}', function ( $missingRoute) {
    // $missingRoute
} )->where('all', '(.*)');

Laravel ships with default error page, You can easily add custom error pages like this

1 - Create an error view in view -> errors folder
2 - The name must match HTTP errors like 404 or 403 500

`Route::get('/page/not/found',function($closure){
  // second param is  optional 
  abort(404, 'Page Not found');
});`

By Adding following code

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

and

public function render($request, Exception $e)
    {
    return redirect('/');
            //return parent::render($request, $e);
    }

will work properly for me


One way you can handle it but it's not the best is to change over to a redirect.

<?php namespace App\Exceptions;

use Exception;
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 = [
                'Symfony\Component\HttpKernel\Exception\HttpException'
        ];

        /**
         * 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)
        {
                return 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)
        {
        return redirect('/');
                //return parent::render($request, $e);
        }

}

참고URL : https://stackoverflow.com/questions/26630985/how-do-i-catch-exceptions-missing-pages-in-laravel-5

반응형