Laravel 5.1 exception processor and HTTP exception handling

Source: Internet
Author: User
Tags error code exception handling getmessage php file stack trace

Errors and exceptions are unavoidable in program development. In local development, we often want to capture and print exceptions thrown by the program, in order to intuitively know where the program is going wrong and solve it, while in the online environment, we do not want to display program errors or exceptions in the browser (for security considerations ), at this time, we still need to capture exceptions, but not to display them in the browser, but to record them in the log for future troubleshooting.

Laravel certainly supports PHP native error and exception handling, but some encapsulation processing is carried out on this basis, making it easier to switch between different development environments and handle errors and exceptions.

1. Configuration

You can use the debug configuration item in the config/app. Php file to determine whether to enable the debugging mode. The default configuration is as follows:

'Debug' => env ('app _ debug', false ),
Of course, the real configuration is in the. env file under the Project root directory. If the value is true, if the program throws an exception, the error exception information is displayed on the page.

2. Exception processor

All Exceptions in Laravel applications are handled by App \ Exceptions \ Handler. Next we will analyze the attributes and methods of the exception processor class:

$ DontReport attribute

Protected $ dontReport = [
HttpException: class,
ModelNotFoundException: class,
];

The $ dontReport attribute defines exceptions that will not be recorded in logs. For example, the default HTTP exception and ModelNotFound exception are not recorded, but the exception information is printed directly in the browser.

Report method

Public function report (Exception $ e)
{
Return parent: report ($ e );
}
The report method calls the Parent report method to record the exception information to the log (we will talk about the log in the next section ).

Render Method

Public function render ($ request, Exception $ e)
{
If ($ e instanceof ModelNotFoundException ){
$ E = new NotFoundHttpException ($ e-> getMessage (), $ e );
    }

Return parent: render ($ request, $ e );
}
The render method renders the exception information to the HTTP response, so that we can intuitively view the error information in the browser during the development process to locate the problem.

Simple test example

The following is a simple test of ModelNotFoundException. As the name suggests, this exception is thrown if the corresponding model instance is not found in the database when the Eloquent ORM is used for query.

As shown in the following example, we compile the test code in the index method of TestController:

$ User = User: findOrFail (100 );
Dd ($ user );

Then access http://laravel.app: 8000/test in the browser, the page will print the error message:

Because ModelNotFoundException is in the $ dontReport attribute array, it is not recorded in the log (NotFoundHttpException is a subclass of HttpException, so it is not recorded in the log). Next we will test the following code:

$ Num = 1/0;
When you access http://laravel.app: 8000/test again, the page prints the error message:

In addition, you can view the written error information in the error log storage/logs/laravel. log:

[21:21:47] local. ERROR: exception 'errorexception 'with message 'division by zero' in/vagrant/laravelapp/app/Http/Controllers/TestController. php: 389
Stack trace:
...
In addition, through the error information, you can know both the cause of the error and the location of the error code in the program, which can greatly save us time to troubleshoot the error and improve programming efficiency.

3. HTTP exception handling

During daily development, we often encounter HTTP error codes such as 404 and 500, indicating that the page is not found or the server is incorrect, laravel provides us with a separate method to handle these error exceptions:

Abort method

We use the abort method to simply throw an HTTP error code exception. If the page is not found or the data does not exist, we use the following method to throw a 404 exception:

Abort (404 );

If server authentication fails, we can throw a 403 exception as follows. Of course, we can also pass in the error message to the abort method:

Abort (403, 'Sorry, you are not authorized to access this page! ');

For pages that throw 403 exceptions, the default display is as follows:

Obviously, such pages cannot be placed in the online environment. How can we create custom views for HTTP exceptions? Don't worry, Laravel has done a comprehensive solution for us:

Error Page View

To create custom HTTP exception views such as 404, 403, and 500, you only need to create the page view file corresponding to the error code in the resources/views/errors directory. For example, to define the custom View with 403 exceptions, you can create the resources/views/errors/403. blade. Php file. Now we can define the following content:

{{$ Exception-> getMessage ()}}
In this way, the 403 exception page is displayed as follows:

Sorry, you are not authorized to access this page!
That's right. It's the content in the 403. blade. Php file. Is it very convenient?

Note: at the underlying layer of the abort method, the corresponding exception is thrown. If the 404 error is thrown, the NotFoundHttpException is thrown. If other HTTP errors are returned, the HTTP exception is thrown.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.