What are the exceptions in 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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.
