Home PHP Framework Laravel What are the exceptions in laravel

What are the exceptions in laravel

Jun 28, 2022 pm 05:53 PM
laravel

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');
        }
    }
}
Copy after login

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);
    }
}
Copy after login

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());
    }
}
Copy after login

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);
}
Copy after login

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;
        }));
    }
}
Copy after login

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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);
}
Copy after login

[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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel - Action URL Laravel - Action URL Aug 27, 2024 am 10:51 AM

Laravel - Action URL - Laravel 5.7 introduces a new feature called “callable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directl

See all articles