Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Created May 4, 2025 09:03
Show Gist options
  • Save atomjoy/348395fc59dbf5e09a4f7abbc6a1f3a2 to your computer and use it in GitHub Desktop.
Save atomjoy/348395fc59dbf5e09a4f7abbc6a1f3a2 to your computer and use it in GitHub Desktop.
Laravel custom exception handler with service provider (modules).

Laravel 12 Custom Exception Handler

Laravel 12 custom exception handler with 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