Error in Handler Class - Laravel

Asked
Active3 hr before
Viewed126 times

7 Answers

classerror
90%

Ignoring Exceptions By Type,When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions thrown by your application are logged and then rendered to the user. We'll dive deeper into this class throughout this documentation.,Laravel Partners are elite shops providing top-notch Laravel development and consulting. Each of our partners can help you craft a beautiful, well-architected project.,Reportable & Renderable Exceptions

For example, if you need to report different types of exceptions in different ways, you may use the reportable method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:

use App\ Exceptions\ InvalidOrderException;

/**
 * Register the exception handling callbacks for the application.
 *
 * @return void
 */
public
function register() {
   $this - > reportable(function(InvalidOrderException $e) {
      //
   });
}
load more v
88%

1 If you re-use lots of code by building vendor packages for yourself, then it may be helpful to make your own Handler class and reference it from the project/bootstrap/app.php . That way you can keep alll your code in packages and use composer to distribute your updates. – Tarek Adam Aug 25 '19 at 17:35 ,Then you should call these methods "report(), render()" inside your custom handler and they will override the existing ones in the App\Exceptions\Handler.,Laravel calls the render function of App\Exceptions\Handler class. So overriding it will not work., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

For example:

< ? php

namespace App\ Exceptions;

use Exception;
use Illuminate\ Auth\ AuthenticationException;
use App\ Project\ Frontend\ Repo\ Vehicle\ EloquentVehicle;
use Illuminate\ Foundation\ Exceptions\ Handler as ExceptionHandler;

class Handler extends ExceptionHandler {
   /**
    * A list of the exception types that should not be reported.
    *
    * @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\ Session\ TokenMismatchException::class, \Illuminate\ Validation\ ValidationException::class, ];

   /**
    * Report or log an exception.
    *
    * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
    *
    * @param  \Exception  $exception
    * @return void
    */
   public
   function report(Exception $exception) {
      parent::report($exception);
   }

   /**
    * Render an exception into an HTTP response.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Exception  $exception
    * @return \Illuminate\Http\Response
    */
   public
   function render($request, Exception $exception) {
      if ($exception instanceof CustomException) {
         return $this - > showCustomErrorPage();
      }

      return parent::render($request, $exception);
   }

   protected
   function showCustomErrorPage() {
      $recentlyAdded = app(EloquentVehicle::class) - > fetchLatestVehicles(0, 12);

      return view() - > make('errors.404Custom') - > with('recentlyAdded', $recentlyAdded);
   }
}
load more v
72%

report() is used if you want to do some additional logging – send error to BugSnag, email, Slack etc.,render() is used if you want to redirect back with error or return HTTP response (like your own Blade file) directly from Exception class,So how can we create our own exception class? Simple, with Artisan command:,“usually controller is calling some kind of external service or package method which may fail with different kinds of errors.”

We have two routes:

Route::get('/users', 'UserController@index') - > name('users.index');
Route::post('/users/search', 'UserController@search') - > name('users.search');
load more v
65%

In the first half of the article, we'll explore the default settings provided by the exception handler. In fact, we'll go through the default Handler class in the first place to understand how Laravel handles exceptions.,Next, let's have a look at the default Handler class that comes with the default Laravel application. Go ahead and open the app/Exceptions/Handler.php file.,Before we go ahead and dive into the Handler class straight away, let's have a look at a couple of important configuration parameters related to exceptions.,In the second half of the article, we prepared a custom exception handler class that demonstrated how you could handle custom exceptions in your application.

Go ahead and open the config/app.php file. Let's have a close look at the following snippet.

...
...
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => env('APP_DEBUG', false),
   ...
   ...
load more v
75%

When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. We'll dive deeper into this class throughout this documentation.,The Exception Handler,The Exception Handler Report Method Render Method ,Monolog has a variety of additional handlers you may use for logging. If needed, you may access the underlying Monolog instance being used by Laravel:

Out of the box, Laravel supports writing log information to single files, daily files, the syslog, and the errorlog. To configure which storage mechanism Laravel uses, you should modify the log option in your config/app.php configuration file. For example, if you wish to use daily log files instead of a single file, you should set the log value in your app configuration file to daily:

'log' => 'daily'
load more v
40%

You can also render different error page using laravel register method inside your App\Exceptions\Handler class. Let's take an example let's create a new exception class that will be called when order fails in our app. , Let say that you want to create a custom response or view for your custom error you can do that in laravel. All you need to do is to modify  App\Exceptions\Handler class. , Let say you have setup laravel rest api and now want to render json error instead of html error in your laravel app for all routes that starts with /api prefix. Open App\Exceptions\Handler class and mondify render function as shown below: , We added this new function called context which returns array you can add any custom key which you can later use in the template file. Let's modify our  App\Exceptions\Handler class as shown below:

You simply create following files and modify the content of the file as per your requirements:

resources
   |
   --views |
   --errors |
   --404. blade.php |
   --401. blade.php |
   --403. blade.php |
   --500. blade.php
load more v
22%

You have to add it in App\Exceptions\Handler class only.,Laravel calls the render function of App\Exceptions\Handler class. So overriding it will not work.,Then you should call these methods "report(), render()" inside your custom handler and they will override the existing ones in the App\Exceptions\Handler.,In new versions of Laravel, you can create a custom handler using this command:

For example:

< ? php

namespace App\ Exceptions;

use Exception;
use Illuminate\ Auth\ AuthenticationException;
use App\ Project\ Frontend\ Repo\ Vehicle\ EloquentVehicle;
use Illuminate\ Foundation\ Exceptions\ Handler as ExceptionHandler;

class Handler extends ExceptionHandler {
   /**
    * A list of the exception types that should not be reported.
    *
    * @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\ Session\ TokenMismatchException::class, \Illuminate\ Validation\ ValidationException::class, ];

   /**
    * Report or log an exception.
    *
    * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
    *
    * @param  \Exception  $exception
    * @return void
    */
   public
   function report(Exception $exception) {
      parent::report($exception);
   }

   /**
    * Render an exception into an HTTP response.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Exception  $exception
    * @return \Illuminate\Http\Response
    */
   public
   function render($request, Exception $exception) {
      if ($exception instanceof CustomException) {
         return $this - > showCustomErrorPage();
      }

      return parent::render($request, $exception);
   }

   protected
   function showCustomErrorPage() {
      $recentlyAdded = app(EloquentVehicle::class) - > fetchLatestVehicles(0, 12);

      return view() - > make('errors.404Custom') - > with('recentlyAdded', $recentlyAdded);
   }
}
load more v

Other "class-error" queries related to "Error in Handler Class - Laravel"