use Zend\Mvc\Controller\AbstractActionController; use Zend\Mvc\MvcEvent; class MyController extends AbstractActionController { public function onDispatch(MvcEvent $e) { // Check if controller is found if (!$this->controllerLoader->has($e->getRouteMatch()->getParam('controller'))) { // Set error message $e->setError('Controller not found'); // Return error response $response = $e->getResponse(); $response->setStatusCode(404); return $response; } } }
use Zend\Mvc\MvcEvent; class MyModule { public function onBootstrap(MvcEvent $e) { // Try to connect to the database try { $pdo = new \PDO($dsn, $username, $password); } catch (\PDOException $ex) { // Set error message $e->setError('Database connection failed'); $e->setParam('exception', $ex); // Return error response $response = $e->getResponse(); $response->setStatusCode(500); return $response; } } }Both examples demonstrate how to use the setError method to set an error message and handle the error in different scenarios. The package library used is Zend Framework (Zend\Mvc\MvcEvent is a part of the Zend\Mvc package).