mistake


Exception handler

Report method

Configuration

The debug option in your config/app.php configuration file determines how much information will actually be displayed to the user for an error. By default, the setting of this option will respect the value of the APP_DEBUG environment variable stored in the .env file.

For local development, you should set the value of the APP_DEBUG environment variable to true . In a production environment, this value should always be false . If you set this value to true in production, you may expose sensitive configuration values ​​to end users of your application.

Exception handler

Report method

All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We will dissect these methods in detail. The report method is used to log exceptions or send them to an external service like Bugsnag or Sentry. By default, the report method passes the exception to the base class that logs the exception. However, you can log exceptions in any way you like.

For example, if you need to report different types of exceptions differently, you can use PHP's instanceof comparison operator:

/**
 * 报告或记录异常
 *
 * 此处是发送异常给 Sentry、Bugsnag 等外部服务的好位置。
 *
 * @param  \Exception  $exception
 * @return void
 */
 public function report(Exception $exception){  
   if ($exception instanceof CustomException) {     
      //    
    }   
   parent::report($exception);
 }

{tip} Don't There are too many instanceof checks in the report method. Consider using a Reportable exception instead.

Global log

Under normal circumstances, Laravel will automatically add the current user's ID as data to each exception log. You can define your global environment variables by overriding the context method in the App\Exceptions\Handler class. Afterwards, this variable will be included in each exception log:

/**
 * 定义默认的环境变量
 *
 * @return array
 */
 protected function context(){  
   return array_merge(parent::context(), [    
       'foo' => 'bar',   
      ]);
   }

report Helper function

Sometimes you may need to report an exception, but You do not want to terminate processing of the current request. report Helper functions allow you to quickly report exceptions without displaying an error page using the exception handler's report method:

public function isValid($value){  
  try {       
   // 验证值...  
   } 
    catch (Exception $e) {  
        report($e);   
        return false;   
      }
   }

Press Type Ignored Exceptions

The $dontReport attribute of the exception handler contains a set of exception types that will not be logged. For example, exceptions caused by 404 errors and several other types of errors are not written to the log file. You can add other exception types to this array as needed:

/**
 * 不应被报告的异常类型清单。
 *
 * @var array
 */protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Validation\ValidationException::class,];

Render Method

render method is responsible for converting the given exception into an HTTP response that will be sent back to the browser. By default, exceptions are passed to the base class that generates the response for you. However, you can check the exception type or return your own custom response if you wish:

/**
 * 将异常转换为 HTTP 响应。
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
 public function render($request, Exception $exception){ 
    if ($exception instanceof CustomException) {     
       return response()->view('errors.custom', [], 500);  
      }  
     return parent::render($request, $exception);
   }

##Reportable & Renderable Exceptions

In addition to checking the exception type in the

report and render methods of the exception handler, you can also define report and ## directly on the custom exception. #render method. When these methods are defined, they will be automatically called by the framework:

<?php
  namespace App\Exceptions;use Exception;
  class RenderException extends Exception{   
        /**
     * 报告异常
     *
     * @return void
     */   
   public function report()  
     {    
       //   
      }    
     /**
     * 转换异常为 HTTP 响应
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */  
    public function render($request) 
       {     
          return response(...); 
        }
     }

{tip} You can declare the
report

method and necessary parameters, and they will be automatically called by Laravel's service container In the injection method

HTTP exception

Some exceptions are used to describe HTTP error codes generated from the server . For example, "Page Not Found" errors (404), "Unauthorized Errors" (401), or even 500 errors caused by developers. You can use the

abort

helper function to generate a response like this from anywhere in your application:

abort(404);
The helper function

abort

will immediately raise an exception rendered by an exception handler . You can also optionally provide response text:

abort(403, 'Unauthorized action.');

Custom HTTP Error Page

Laravel can easily display Custom error pages for various HTTP status codes. For example, if you want to customize the error page for 404 HTTP status codes, you can create a

resources/views/errors/404.blade.php

view file. This file will be used for all 404 errors generated by your application. View files in this directory should be named to match their corresponding HTTP status codes. The HttpException instance thrown by the abort function will be passed to the view as the $exception variable:

<h2>{{ $exception->getMessage() }}</h2>
You can use

vendor:publish

Artisan commands to define error template pages. After the template page is generated, you can customize the content of the template page:

php artisan vendor:publish --tag=laravel-errors
This article was first published on the

LearnKu.com
website.