Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Created February 5, 2025 09:53
Show Gist options
  • Save atomjoy/b0b32d5067431a963a8f526dc6caad91 to your computer and use it in GitHub Desktop.
Save atomjoy/b0b32d5067431a963a8f526dc6caad91 to your computer and use it in GitHub Desktop.
Laravel 11 Exception Handler with Service Provider.

Laravel 11 Exception Handler

Reportable and renderable methods in exception handler with Laravel 11 service provider (modules).

ExceptionHandlerProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Debug\ExceptionHandler as AppExceptionHandler;
use App\Exception\Handler;

class ExceptionHandlerProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(AppExceptionHandler::class, Handler::class);
    }
}

Handler.php

<?php

namespace App\Exception;

use Throwable;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof \Exception) {
            // Custom error handling logic for HTTP requests
        }

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

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        // Model not found exception
        $this->renderable(function (NotFoundHttpException $e, Request $request) {
            if ($request->is('web/api/*')) {
                return response()->json([
                    'message' => 'Record not found.'
                ], 404);
            }
        });
    }
}

provider.php

<?php

return [
    App\Providers\AppServiceProvider::class,
    App\Providers\ExceptionHandlerProvider::class,
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment