[laravel] 에러처리하기

[laravel] 에러처리하기 updated_at: 2024-07-15 14:42

에러대처하기

에러페이지 생성

아래처럼 command를 실행하면 /resources/views/errors 폴더 아래로 다양항 에러 페이지가 생성된다.

php artisan vendor:publish --tag=laravel-errors

에러페이지 처리

"The GET method is not supported for this route. Supported methods: POST"

위와 같은 메시지를 도출할때도 간단하게 에러페이지로 redirect 시킬 수 있다.

  • app/Exceptions/Handler.php

기본 파일

namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{

  protected $dontReport = [
      //
  ];

  protected $dontFlash = [
    'current_password',
    'password',
    'password_confirmation',
  ];

  public function register()
  {
    $this->reportable(function (Throwable $e) {
      //
    });
  }
}

수정 파일

아래의 내용들을 추가한다.

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; // 추가 1

class Handler extends ExceptionHandler
{

  ..........
  /**
   * Render an exception into an HTTP response.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Throwable  $e
   * @return \Symfony\Component\HttpFoundation\Response
   *
   * @throws \Throwable
   */
  public function render($request, Throwable $e)  // 추가 2
  {
      if ($e instanceof MethodNotAllowedHttpException) {
          return abort(404);
      }
      
      return parent::render($request, $e);
  }
}

평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글