Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom exception class and custom handler class in Laravel 5.3

Before I get to the code, let me explain my aim. My web app displays vehicles for sale. I have a need for a custom 404 page that will display 12 of the latest vehicles added to the database if the user tries to access a page that doesn't exist.

I have the following...

App\Exceptions\CustomException.php

<?php

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
    public function __construct()
    {
        parent::__construct();
    }
}

App\Exceptions\CustomHandler.php

<?php
namespace App\Exceptions;

use Exception;
use App\Exceptions\Handler as ExceptionHandler;
use Illuminate\Contracts\Container\Container;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Foundation\Exceptions\Handler;
use Illuminate\Support\Facades\View;

class CustomHandler extends ExceptionHandler
{
    protected $vehicle;

    public function __construct(Container $container, EloquentVehicle $vehicle)
    {
        parent::__construct($container);

        $this->vehicle = $vehicle;
    }

    /**
     * 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)
    {
        $exception = Handler::prepareException($exception);

        if($exception instanceof CustomException) {
            return $this->showCustomErrorPage();
        }

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

    public function showCustomErrorPage()
    {
        $recentlyAdded = $this->vehicle->fetchLatestVehicles(0, 12);

        return View::make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
    }
}

To test this I added

throw new CustomException();

to my controller but it doesn't bring up the 404Custom view. What do I need to do to get this working?

UPDATE: Just a note for anyone who's bound their class to their model. You'll get a BindingResolutionException if you try to access a function in your class using:

app(MyClass::class)->functionNameGoesHere();

To get around this simply create a variable in the same way you would bind your class to the Container in your service provider.

My code looks like this:

protected function showCustomErrorPage()
{
    $eloquentVehicle = new EloquentVehicle(new Vehicle(), new Dealer());
    $recentlyAdded = $eloquentVehicle->fetchLatestVehicles(0, 12);

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

Amit's version

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

    return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
like image 602
VenomRush Avatar asked Nov 10 '16 09:11

VenomRush


People also ask

How do I create a custom exception class?

Steps to create a Custom Exception with an ExampleCreate one local variable message to store the exception message locally in the class object. We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message.

What is exception handler in laravel?

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.

What is laravel handler?

Laravel Handlers is a package by Ilya Sakovich for creating single-action request handlers. The idea of a request handler is a single-action controller which means that a unique class handles each request.


2 Answers

Step 1: Create a custom Exception

php artisan make:exception CustomException

Step 2: Include that exception in your code

use App\Exceptions\CustomException;

Pass your error to that Exception

if($somethingerror){
  throw new CustomException('Your error message');          
}

Step 3: Handle your exception in CustomException file in report() and render() methods

For example, if I want display the error as JSON format

<?php
namespace App\Exceptions;
use Exception;
class CustomException extends Exception
{   
    public function render($request)
    {       
        return response()->json(["error" => true, "message" => $this->getMessage()]);       
    }
}
like image 61
Giangimgs Avatar answered Oct 13 '22 20:10

Giangimgs


In new versions of Laravel, you can create a custom handler using this command:

php artisan make:exception CustomException

Then you should call these methods "report(), render()" inside your custom handler and they will override the existing ones in the App\Exceptions\Handler.

report() used if you want to log the errors.

render() used if you want to redirect back with error or return HTTP response (like your own Blade file) or if you're building an API.

For more information, you can check Laravel documentation.

like image 21
Ali Ali Avatar answered Oct 13 '22 20:10

Ali Ali