0

I have recently created a new project in Laravel 11 and can not get my custom error handling class to work. I have a class I use throughout all my Larvael projects (laravel 10). I want to use this class in Laravel 11 to process all my errors, but it seems the new version relies on the withExceptions method in app.php

->withExceptions(function (Exceptions $exceptions) {

Does anyone know how I can get the withExceptions class to still use this (or any) external class for handling


use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

}
1

1 Answer 1

2

In Laravel 11, exception handling with custom classes registration has changed. To use your custom handler:

  1. Create your custom handler:
namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class CustomHandler extends ExceptionHandler
{
    public function render($request, Throwable $e)
    {
        // Custom logic
        return response()->json(['error' => $e->getMessage()], 500);
    }
}
  1. Register it in bootstrap/app.php:
$app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\CustomHandler::class );

You can inject external classes into CustomHandler for additional processing.


More details:


Sign up to request clarification or add additional context in comments.

4 Comments

I tried this but I get - Error: Call to undefined method Illuminate\Foundation\Configuration\Exceptions::handler() in file /var/www/html/appName/bootstrap/app.php on line 71
Ah I see, they removed handler as well. Can you please try with singleton and see if it works? $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\CustomHandler::class );
Thanks, that’s worked. Do you want to edit your answer to include then singleton and then I’ll mark it correct :)
Updated the answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.