Home  >  Article  >  PHP Framework  >  What are the exceptions in laravel

What are the exceptions in laravel

青灯夜游
青灯夜游Original
2022-06-28 17:53:332678browse

Exceptions in laravel include: 1. "E_ERROR" fatal runtime error, which is unrecoverable and will cause the script to terminate and not continue running; 2. "E_WARNING" runtime warning "non-fatal error"; 3. "E_PARSE" compile-time syntax parsing error; 4. "E_CORE_ERROR" fatal error that occurs during initialization and startup; 5. "E_COMPILE_ERROR" fatal compile-time error; 6. "E_RECOVERABLE_ERROR" fatal error that can be captured.

What are the exceptions in laravel

The operating environment of this tutorial: Windows 7 system, Laravel 9 version, DELL G3 computer.

Exception level in laravel

Constant Description
E_ERROR Fatal runtime error. This type of error is generally an unrecoverable situation, such as a problem caused by memory allocation. The consequence is that the script terminates and does not continue to run.
E_WARNING Run-time warning (non-fatal error). Only a prompt message is given, but the script does not terminate.
E_PARSE Compile-time syntax parsing error. Parsing errors are generated only by the parser.
E_NOTICE Runtime notification. Indicates that the script encounters a situation that may appear as an error, but there may also be similar notifications in scripts that can run normally.
E_CORE_ERROR A fatal error occurred during PHP initialization startup. This error is similar to E_ERROR, but is generated by the PHP engine core.
E_CORE_WARNING A warning (non-fatal error) occurred during PHP initialization startup. Like E_WARNING, but generated by the PHP engine core.
E_COMPILE_ERROR Fatal compile-time error. Similar to E_ERROR, but generated by the Zend scripting engine.
E_COMPILE_WARNING Compile-time warning (non-fatal error). Like E_WARNING, but generated by the Zend scripting engine.
E_USER_ERROR User-generated error message. Similar to E_ERROR, but is generated by the user using the PHP function trigger_error () in the code.
E_USER_WARNING Warning message generated by the user. Similar to E_WARNING, but is generated by the user using the PHP function trigger_error () in the code.
E_USER_NOTICE Notification information generated by the user. Similar to E_NOTICE, but is generated by the user using the PHP function trigger_error () in the code.
E_STRICT Enable PHP's suggestions for code modifications to ensure the best interoperability and forward compatibility of the code.
E_RECOVERABLE_ERROR A fatal error that can be caught. It indicates that a potentially dangerous error has occurred, but has not yet left the PHP engine in an unstable state. If the error is not caught by a user-defined handler (see set_error_handler ()), it will become an E_ERROR and the script will terminate.
E_DEPRECATED Runtime notification. When enabled, a warning will be given about code that may not work properly in future versions.
E_USER_DEPRECATED User generated warning message. Similar to E_DEPRECATED, but is generated by the user using the PHP function trigger_error () in the code.
E_ALL User generated warning message. Similar to E_DEPRECATED, but is generated by the user using the PHP function trigger_error () in the code.

Laravel exception handling

Laravel's exception handling is completed by the class \Illuminate\Foundation\Bootstrap\HandleExceptions::class:

class HandleExceptions
{
    public function bootstrap(Application $app)
    {
        $this->app = $app;

        error_reporting(-1);

        set_error_handler([$this, 'handleError']);

        set_exception_handler([$this, 'handleException']);

        register_shutdown_function([$this, 'handleShutdown']);

        if (! $app->environment('testing')) {
            ini_set('display_errors', 'Off');
        }
    }
}

Exception conversion

Laravel's exception handling is all handled by the function handleException.

PHP7 implements a global throwable interface. The original Exception and some Errors implement this interface, and define the inheritance structure of exceptions in the form of interfaces. As a result, more Errors in PHP7 become catchable Exceptions and are returned to developers. If they are not caught, they are Errors. If they are caught, they become Exceptions that can be handled within the program. These catchable Errors are usually Errors that do not cause fatal harm to the program, such as a function that does not exist.

In PHP7, based on /Error exception, 5 new engine exceptions are derived: ArithmeticError / AssertionError / DivisionByZeroError / ParseError / TypeError. In PHP7, both the old /Exception and the new /Error implement a common interface: /Throwable.

Therefore, when encountering an exception of non-Exception type, you must first convert it into a FatalThrowableError type:

public function handleException($e)
{
    if (! $e instanceof Exception) {
        $e = new FatalThrowableError($e);
    }

    $this->getExceptionHandler()->report($e);

    if ($this->app->runningInConsole()) {
        $this->renderForConsole($e);
    } else {
        $this->renderHttpResponse($e);
    }
}

FatalThrowableError is an error exception class that Symfony inherits \ErrorException:

class FatalThrowableError extends FatalErrorException
{
    public function __construct(\Throwable $e)
    {
        if ($e instanceof \ParseError) {
            $message = 'Parse error: '.$e->getMessage();
            $severity = E_PARSE;
        } elseif ($e instanceof \TypeError) {
            $message = 'Type error: '.$e->getMessage();
            $severity = E_RECOVERABLE_ERROR;
        } else {
            $message = $e->getMessage();
            $severity = E_ERROR;
        }

        \ErrorException::__construct(
            $message,
            $e->getCode(),
            $severity,
            $e->getFile(),
            $e->getLine()
        );

        $this->setTrace($e->getTrace());
    }
}

Exception Log

When encountering an abnormal situation, the first thing laravel does is to record the log. This is the role of the report function.

protected function getExceptionHandler()
{
    return $this->app->make(ExceptionHandler::class);
}

laravel's default exception handling class in the Ioc container is Illuminate\Foundation\Exceptions\Handler:

class Handler implements ExceptionHandlerContract
{
    public function report(Exception $e)
    {
        if ($this->shouldntReport($e)) {
            return;
        }
        try {
            $logger = $this->container->make(LoggerInterface::class);
        } catch (Exception $ex) {
            throw $e; // throw the original exception
        }
        $logger->error($e);
    }
    protected function shouldntReport(Exception $e)
    {
        $dontReport = array_merge($this->dontReport, [HttpResponseException::class]);
        return ! is_null(collect($dontReport)->first(function ($type) use ($e) {
            return $e instanceof $type;
        }));
    }
}

Exception page display

Record log After that, it is necessary to convert the exception into a page to display the exception information to the developer in order to check the source of the problem:

protected function renderHttpResponse(Exception $e)
{
    $this->getExceptionHandler()->render($this->app['request'], $e)->send();
}
class Handler implements ExceptionHandlerContract
{
    public function render($request, Exception $e)
    {
        $e = $this->prepareException($e);
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } elseif ($e instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($e, $request);
        }
        return $this->prepareResponse($request, $e);
    }
}

For different exceptions, laravel has different processing, roughly including HttpException, HttpResponseException, AuthorizationException, ModelNotFoundException , AuthenticationException, ValidationException. Since specific different exceptions have their own different needs, this article will not specifically introduce them. This article continues to introduce the handling of the most common exception HttpException:

protected function prepareResponse($request, Exception $e)
{
    if ($this->isHttpException($e)) {
        return $this->toIlluminateResponse($this->renderHttpException($e), $e);
    } else {
        return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
    }
}
protected function renderHttpException(HttpException $e)
{
    $status = $e->getStatusCode();
    view()->replaceNamespace('errors', [
        resource_path('views/errors'),
        __DIR__.'/views',
    ]);
    if (view()->exists("errors::{$status}")) {
        return response()->view("errors::{$status}", ['exception' => $e], $status, $e->getHeaders());
    } else {
        return $this->convertExceptionToResponse($e);
    }
}

For HttpException, different error page templates will be selected according to its error status code. If there is no relevant template, it will be sent through SymfonyResponse Construct exception display page:

protected function convertExceptionToResponse(Exception $e)
{
    $e = FlattenException::create($e);
    $handler = new SymfonyExceptionHandler(config('app.debug'));
    return SymfonyResponse::create($handler->getHtml($e), $e->getStatusCode(), $e->getHeaders());
}
protected function toIlluminateResponse($response, Exception $e)
{
    if ($response instanceof SymfonyRedirectResponse) {
        $response = new RedirectResponse($response->getTargetUrl(), $response->getStatusCode(), $response->headers->all());
    } else {
        $response = new Response($response->getContent(), $response->getStatusCode(), $response->headers->all());
    }
    return $response->withException($e);
}

[Related recommendations: laravel video tutorial]

The above is the detailed content of What are the exceptions in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what is laravel forgeNext article:what is laravel forge