I want to create a custom exception class in my Laravel project to handle specific types of errors. Can someone guide me on how to create our own exception class and how to use it in the application?
You can use Laravel’s Artisan command to generate a custom exception class quickly. Here’s how you can do it:
- Generate Custom Exception Class with Artisan:
Use themake:exception
Artisan command to generate custom exception class.
php artisan make:exception CustomException
This command will create a new PHP class file CustomException.php
inside the app/Exceptions
directory.
- Define Your Custom Exception Class:
namespace App\Exceptions;
use Exception;
use Throwable;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
class CustomException extends Exception
{
public $errors;
public function __construct($message = "", $code = 0, $errors = [], Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->errors = $errors;
}
public function render()
{
return [
'error' => true,
'code' => $this->code,
'message' => $this->getMessage(),
'errors' => $this->errors
];
}
public function getErrors()
{
return response()->json($this->errors, $this->code);
}
public function report()
{
Log::error($this->getMessage());
}
}
- Throw Your Custom Exception:
Now throw your custom exception wherever necessary in your application, just like any other exception.
if (!$condition) {
throw new CustomException("Something went wrong. This is a custom error message.");
}
- Handle Your Custom Exception:
You can catch and handle your custom exception just like any other exception.
try {
} catch (CustomException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}