Symfony is a popular PHP framework known for its robust error handling and exception system. Exceptions are a way to handle and report errors or exceptional situations that occur during the execution of a Symfony application.
Symfony provides a set of built-in exception classes that can be used to handle specific types of errors in a standardized manner. By utilizing these exceptions, developers can handle errors and exceptional cases in a structured and consistent way, improving the maintainability and robustness of Symfony applications.
Most commonly used Symfony exceptions
NotFoundHttpException
This exception is thrown when a requested resource or route is not found. It is commonly used to handle 404 errors.
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// Example usage
if ($resourceNotFound) {
throw new NotFoundHttpException('The requested resource was not found.');
}
AccessDeniedException
This exception is thrown when a user is denied access to a resource or action due to insufficient permissions.
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
// Example usage
if (!$user->hasPermission('edit_post')) {
throw new AccessDeniedException('You do not have permission to edit this post.');
}
InvalidArgumentException
This exception is thrown when there is an invalid argument passed to a form-related operation.
use Symfony\Component\Form\Exception\InvalidArgumentException;
// Example usage
if ($formField === null) {
throw new InvalidArgumentException('Invalid form field provided.');
}
RouteNotFoundException
This exception is thrown when a named route is not found.
use Symfony\Component\Routing\Exception\RouteNotFoundException;
// Example usage
if (!$router->getRouteCollection()->get('my_route')) {
throw new RouteNotFoundException('The named route "my_route" was not found.');
}
FileNotFoundException
This exception is thrown when a file is not found.
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
// Example usage
if (!file_exists($filePath)) {
throw new FileNotFoundException('The file "' . $filePath . '" was not found.');
}
Custom Exceptions
Create a new PHP class that represents your custom exception.
This class should extend Exception or one of its child classes, such as RuntimeException
or LogicException
. For example, let's create a custom exception called CustomException
// src/Exception/CustomException.php
namespace App\Exception;
use Exception;
class CustomException extends Exception
{
// You can define custom logic or properties specific to your exception
}
Optionally, you can add additional logic or properties to your custom exception class based on your requirements.
In your application code, whenever you encounter a specific exceptional situation, you can throw your custom exception. For example:
// src/Controller/SomeController.php
namespace App\Controller;
use App\Exception\CustomException;
class SomeController
{
public function someAction()
{
// Some exceptional condition
if ($somethingUnexpected) {
throw new CustomException('Something unexpected occurred.');
}
}
}
In this example, whenever $somethingUnexpected
evaluates to true, the CustomException
will be thrown with a descriptive error message.
To handle the thrown exception, you can either catch it in the same method or propagate it up the call stack to be caught at a higher level. Here's an example of catching and handling the CustomException
// src/Controller/SomeController.php
namespace App\Controller;
use App\Exception\CustomException;
use Symfony\Component\HttpFoundation\Response;
class SomeController
{
public function someAction()
{
try {
// Some exceptional condition
if ($somethingUnexpected) {
throw new CustomException('Something unexpected occurred.');
}
// Rest of the code
} catch (CustomException $exception) {
// Handle the exception
$errorMessage = $exception->getMessage();
$response = new Response($errorMessage, 500);
// Additional response customization can be done here
return $response;
}
}
}
In this example, the CustomException
is caught within the someAction()
method, and a custom response is returned to handle the error.
By creating and throwing custom exceptions, you can have more granular control over the exceptional situations in your Symfony application and provide meaningful error messages or handle them differently based on your application's requirements.