Display php errors when using Zend framework

Asked
Active3 hr before
Viewed126 times

6 Answers

usingerrorsdisplay
90%

To assist in debugging during development, you can use the standard:,Also, if you're using the new Autoloader included with 1.8, use:,This will use the development settings in your application/configs/application.ini file. Those settings define whether to suppress errors.,There seem to be some problems that Zend Framework will fail and display the error through php, like if a certain function doesn't exist or something. Those I can see and fix.

To assist in debugging during development, you can use the standard:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');

Also, if you're using the new Autoloader included with 1.8, use:

Zend_Loader_Autoloader::getInstance() - > suppressNotFoundWarnings(false);
load more v
88%

There seem to be some problems that Zend Framework will fail and display the error through php, like if a certain function doesn't exist or something. Those I can see and fix.,There are certain problems within the Zend framework that Zend can recognize (such as calling a nonexistent controller), and will send that problem to the ErrorController. I've got that working fine.,In addition, many of the factories in Zend Framework utilize the config object to create instances. Zend_Db is a good example of this. You just pass it $this->database and it will take what it needs to instantiate your adapter.,I've been using Zend Framework and just living with this problem for a while, but it's now just gotten too annoying so i'll send the question out to you.

To assist in debugging during development, you can use the standard:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');

Also, if you're using the new Autoloader included with 1.8, use:

Zend_Loader_Autoloader::getInstance() - > suppressNotFoundWarnings(false);
load more v
72%

Zend Framework 3 is a free and open-source PHP framework. It uses a model-view-controller (MVC) pattern which makes its structure consistent and maintainable. It also accesses the database in an object-oriented way. Instead of directly interacting with the database using SQL queries, you can use doctrine object-relational mapping (ORM) to manage the structure and relationships of your data. This makes code easier to write and maintain., Quarkus vs Spring Boot: Which Framework is Right for You? Read more ,"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.",You can get more information about what generated the error by clicking on the item. It then shows the full traceback including the code file, method, and line number. This helps in finding the root cause of the error.

The easiest and most basic way to handle errors is using try, catch, and finally statements. When an error is thrown in the try block, the catch block executes and handles the error. For example, you may want to record the error or present a more friendly error message to the user.

try {
   $value = 5 / 0;
} catch (\Exception $e) {
   echo $e - > getMessage();
}
load more v
65%

zend-log can also be used to log PHP errors and exceptions. You can log PHP errors using the static method Logger::registerErrorHandler($logger) and intercept exceptions using the static method Logger::registerExceptionHandler($logger).,First, we create an error handler listener that composes a logger, and logs the information:,You can install zend-log using the following composer command:,We can then write a delegator factory that will register this as a listener on the ErrorHandler:

You can install zend-log using the following composer command:

composer require zendframework / zend - log
load more v
75%

If you follow these guidelines, you can then write or use middleware that does the following:,sets an error handler that converts PHP errors to ErrorException instances.,When errors occur, you may want to listen for them in order to provide features such as logging. Zend\Stratigility\Middleware\ErrorHandler provides the ability to do so via its attachListener() method.,The response provided is the response returned by your error response generator, allowing the listener the ability to introspect the generated response as well.

We recommend that your code raise exceptions for conditions where it cannot gracefully recover. Additionally, we recommend that you have a reasonable PHP error_reporting setting that includes warnings and fatal errors:

error_reporting(E_ALL & ~E_USER_DEPRECATED & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);

As an example:

function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
   set_error_handler(function($errno, $errstr, $errfile, $errline) {
      if (!(error_reporting() & $errno)) {
         // Error is not in mask
         return;
      }
      throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
   });

   try {
      $response = $handler - > handle($request);
      return $response;
   } catch (Throwable $e) {}

   restore_error_handler();

   $response = new TextResponse(sprintf(
      "[%d] %s\n\n%s",
      $e - > getCode(),
      $e - > getMessage(),
      $e - > getTraceAsString()
   ), 500);
}

You would then pipe this as the outermost (or close to outermost) layer of your application:

$app - > pipe($errorMiddleware);

Map the service Zend\Expressive\Middleware\ErrorResponseGenerator to one of these two factories in your configuration:

use Zend\ Expressive\ Container;
use Zend\ Expressive\ Middleware;
use Zend\ Stratigility\ Middleware\ ErrorHandler;

return [
   'dependencies' => [
      'factories' => [
         ErrorHandler::class => Container\ ErrorHandlerFactory::class,
         Middleware\ ErrorResponseGenerator::class => Container\ ErrorResponseGeneratorFactory::class,
      ],
   ],
];

If you are using zf-development-mode in your application (which is provided by default in the skeleton application), you can toggle usage of whoops by adding configuration to the file config/autoload/development.local.php.dist:

use Zend\ Expressive\ Container;
use Zend\ Expressive\ Middleware;

return [
   'dependencies' => [
      'factories' => [
         Middleware\ WhoopsErrorResponseGenerator::class => Container\ WhoopsErrorResponseGeneratorFactory::class,
      ],
   ],
];

This method accepts a callable with the following signature:

function(
   Throwable $error,
   ServerRequestInterface $request,
   ResponseInterface $response
): void

As an example, you could create a logging listener as follows:

namespace Acme;

use Exception;
use Psr\ Log\ LoggerInterface;
use Psr\ Http\ Message\ ResponseInterface;
use Psr\ Http\ Message\ ServerRequestInterface;
use Throwable;

class LoggingErrorListener {
   /**
    * Log format for messages:
    *
    * STATUS [METHOD] path: message
    */
   const LOG_FORMAT = '%d [%s] %s: %s';

   private $logger;

   public
   function __construct(LoggerInterface $logger) {
      $this - > logger = $logger;
   }

   public
   function __invoke(Throwable $error, ServerRequestInterface $request, ResponseInterface $response) {
      $this - > logger - > error(sprintf(
         self::LOG_FORMAT,
         $response - > getStatusCode(),
         $request - > getMethod(),
         (string) $request - > getUri(),
         $error - > getMessage()
      ));
   }
}

You could then use a delegator factory to create your logger listener and attach it to your error handler:

namespace Acme;

use Psr\ Container\ ContainerInterface;
use Psr\ Log\ LoggerInterface;
use Zend\ Stratigility\ Middleware\ ErrorHandler;

class LoggingErrorListenerDelegatorFactory {
   public
   function __invoke(ContainerInterface $container, string $name, callable $callback): ErrorHandler {
      $listener = new LoggingErrorListener($container - > get(LoggerInterface::class));
      $errorHandler = $callback();
      $errorHandler - > attachListener($listener);
      return $errorHandler;
   }
}

You could also write more specific error handlers. As an example, you might want to catch UnauthorizedException instances specifically, and display a login page:

function(ServerRequestInterface $request, RequestHandlerInterface $handler) use($renderer): ResponseInterface {
   try {
      $response = $handler - > handle($request);
      return $response;
   } catch (UnauthorizedException $e) {}

   return new HtmlResponse(
      $renderer - > render('error::unauthorized'),
      401
   );
}

You could then push this into a middleware pipe only when it's needed:

$app - > get('/dashboard', [
   $unauthorizedHandlerMiddleware,
   $middlewareThatChecksForAuthorization,
   $middlewareBehindAuthorizationWall,
], 'dashboard');

We provide a factory, Zend\Expressive\Container\NotFoundHandlerFactory, for creating an instance, which we detail elsewhere. You should pipe it as the innermost layer of your application:

// A basic application:
$app - > pipe(ErrorHandler::class);
// . . .
$app - > pipe(RouteMiddleware::class);
// . . .
$app - > pipe(DispatchMiddleware::class);
$app - > pipe(NotFoundHandler::class);
load more v
40%

We can configure the default error settings in the application configuration file, myapp/module/Application/config/module.config.php.,The partial code sample is as follows −,The most important item among these is the error/index. This is the template shown when an exception occurs in the system. We can modify this template, myapp/module/Application/view/error/index.phtml to control the amount of error to be shown.,The Error Handler displays errors when the debug is true and logs the error when the debug is false. Zend Framework has several exception classes and the built-in exception handling will capture any uncaught exception and render a useful page.

The partial code sample is as follows −

'view_manager' => [
   'display_not_found_reason' => true,
   'display_exceptions' => true,
   'doctype' => 'HTML5',
   'not_found_template' => 'error/404',
   'exception_template' => 'error/index',
   'template_map' => [
      'layout/layout' => __DIR__.
      '/../view/layout/layout.phtml',
      'application/index/index' => __DIR__.
      '/../view/application/index/index.phtml',
      'error/404' => __DIR__.
      '/../view/error/404.phtml',
      'error/index' => __DIR__.
      '/../view/error/index.phtml',
   ],
   'template_path_stack' => [
      __DIR__.
      '/../view',
   ],
],

Other "using-errors" queries related to "Display php errors when using Zend framework"