Home > Net >  Laravel 8 Handler Undefined class 'Exception'
Laravel 8 Handler Undefined class 'Exception'

Time:01-11

I work in API Laravel project and try to handler "message": "No query results for model ID" and page 404

I use this function but don't send anything in API and no effect on 404 pages

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Handler extends ExceptionHandler
{

public function render($request, Exception $e)
    {
        // "message": "No query results for model ID" in API
        if ($e instanceof ModelNotFoundException) {
            return response()->json(['error' => 'Data not found.']);
        }

        if($this->isHttpException($e))
        {
            switch ($e->getStatusCode())
            {
                // not found
                case 404:
                    return redirect()->guest('home');
                    break;

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

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

}

CodePudding user response:

Use Throwable not Exception

public function render($request, Throwable $e)
    {
        // "message": "No query results for model ID" in API
        if ($e instanceof ModelNotFoundException) {
            return response()->json(['error' => 'Data not found.']);
        }
        return parent::render($request, $e);
    }
  •  Tags:  
  • Related