search
HomePHP FrameworkLaravelWhat 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');
        }
    }
}

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
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version