Exception handler and HTTP exception handling in Laravel 5.1 abort ()

Source: Internet
Author: User

OriginalHttp://laravelacademy.org/post/1867.html

Errors and exceptions are an unavoidable issue in the development of handlers, and in local development we often want to capture the exceptions thrown by the program and print it out so that we can intuitively know where the program has gone wrong and resolve it, while the online environment we do not want to display program errors or exceptions in the browser (for security reasons), This time we still have to catch the exception, but not to display in the browser, but recorded in the log, easy to troubleshoot problems later.

Laravel of course support PHP native error and exception handling, but on this basis a number of encapsulation processing, which makes it easier to switch between different development environments and the handling of errors and exceptions.

1. Configuration

We can config/app.php debug decide whether to turn on debug mode by configuring the item in the file, the default configuration is as follows:

' Debug ' = env (' App_debug ', false),

Of course, the actual configuration of the files located in the project root directory .env , if the value is true , if the program throws an exception will display error exception information in the page.

2. Exception Processor

Laravel all the exceptions in the application are App\Exceptions\Handler handled, let's briefly analyze the properties and methods for the exception handler class:

$dontReport Properties
protected $dontReport = [    httpexception::class,    Modelnotfoundexception::class,];

$dontReportAttributes define exceptions that are not logged, such as default HTTP exceptions and exceptions, and ModelNotFound print exception information directly in the browser.

Report Method
Public Function report (Exception $e) {    return parent::report ($e);}

reportMethod calls the parent's method to log the report exception information to the journal (we'll talk about the log in the next section).

Render Method
Public function render ($request, Exception $e) {    if ($e instanceof modelnotfoundexception) {        $e = new NOTFOUNDHT Tpexception ($e->getmessage (), $e);    }    Return Parent::render ($request, $e);}

renderMethod renders the exception information to the HTTP response, allowing us to visually view the error information in the browser during development to find the problem.

Simple Test Example

Let's take a simple test ModelNotFoundException , as the name implies, when querying with eloquent ORM, the corresponding model instance is not found in the database and throws the exception.

We routinely write the test code in the TestController index method as follows:

$user = User::findorfail (+);dd($user);

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

Because ModelNotFoundException in $dontReport an array of attributes, and therefore not recorded in the log (which NotFoundHttpException is HttpException the subclass, so it is not logged to the log), we then test the following code:

$num = 1/0;

Again, the http://laravel.app:8000/test page will print an error message:

In addition, storage/logs/laravel.log error messages written in the error log can be seen:

[2015-11-08 21:21:47] Local. Error:exception ' errorexception ' with message ' division by zero ' in/vagrant/laravelapp/app/http/controllers/ Testcontroller.php:389stack Trace: ...

Moreover, through these error messages, you can know the cause of the error, but also know the location of the error code in the program, can greatly save us the time to troubleshoot the cause of the error, improve programming efficiency.

3. HTTP Exception Handling

In daily development, we often encounter HTTP error codes such as 404 and 500, which indicate that the page is not found or the server is wrong, and Laravel provides us with a separate way 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 the server authorization fails, we can throw the 403 exception by the following way, and of course, we can also pass the error message to the abort method:

Abort (403, ' Sorry, you don't have permission to access this page! ‘);

For pages that throw 403 exceptions, the default displays are as follows:

Such a page is obviously not put on the online environment, how should you create a custom view for HTTP exceptions? Don't worry, Laravel has done a thorough deal for us:

error Page view

If you want to create a custom view of HTTP exceptions such as 404, 403, 500, you resources/views/errors can simply create a page view file that corresponds to the error code in the catalog. For example, to define the above 403 exception custom view, you can create resources/views/errors/403.blade.php a file, now we simply define its contents as follows:

{{$exception->getmessage ()}}}

This tests the 403 exception page again, as shown below:

Sorry, you do not have permission to access this page!

Yes, it is 403.blade.php the contents of the document, is not very convenient?

Note: The abort underlying method throws a corresponding exception, a 404 error is thrown NotFoundHttpException , and other HTTP errors are thrown HttpException .

Exception handler and HTTP exception handling in Laravel 5.1 abort ()

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.