A free and open-source book on Zend Framework for beginners


4.8. Expressing Error Conditions

Sometimes things go wrong and some error occurs. For example, you expect to receive a GET variable from HTTP request, but it is missing or has an invalid value. To express this error condition, you typically set 4xx status code in HTTP response and return from controller's action.

For example, in a Blog application, assume a user enters the following URL in his browser's navigation bar: http://localhost/posts/view?id=10000. The intention of such request is to display the blog post with ID=10000. If the post with such ID doesn't exist, we can't display it and use the following code to set 404 status code (Page Not Found) for the response:

// The "view" action displays a blog post with the given ID
public function viewAction()
{
    // Get ID argument from GET
    $id = (int)$this->params()->fromQuery('id', -1);
    
    // Validate the argument
    if ($id<1) {
        // Error condition - we can not display such post
        $this->getResponse()->setStatusCode(404);
        return;
    }
    
    // Try to find the post (we omit the actual SQL query for simplicity).
    $post = ...
    if (!$post) {
        // Error condition - post not found
        $this->getResponse()->setStatusCode(404);
        return;
    }
    
    // Normal execution
    // ...
}

When ZF3 encounters the 4xx status code in response, it redirects the user to a special error page. We will talk about error pages later in this chapter.

Another way to express a (critical) error condition is to throw an Exception, for example, like this:

throw new \Exception("Post with ID=$id could not be found");

When ZF3 encounters an unhandled exception, it displays another error page with the information about the exception.


Top