简体   繁体   中英

ZF2 Controller Specific 404 Error Page

I've the following controller

class TitleController extends AbstractActionController {

    public function showAllTitleAction() {
        //Here I've some service that fetch entries from db
        $data = $this->getData();


        if (count($data) == 0) {
            //If data is empty, get 404 code for SEO reasons.
            $this->getResponse()->setStatusCode(404);
        }

        //Although data is empty, go on creating the specific view for this controller
        $viewModel = new ViewModel($data);
        $viewModel->setTemplate('application/title/template');
        return $viewModel;
    }
}

When I give 404 error in the controller, my request is intercepted and I get the default 404 error page. But I just want to change HTTP status code, not the content. (I'll show a friendly message in the output)

How can I prevent my request to be intercepted by the default 404 page?

Thanks.

Well I can't really understand why you'd want that (if it's 404 then there shouldn't be any content for display), but for the sake of argument, I suppose you could:

  1. register a listener for EVENT_DISPATCH_ERROR event before the default RouteNotFoundStrategy ,
  2. stop event propagation in that listener and return whatever you want (see the links bellow)

You could also go down the route of:

  1. throwing an exception instead of changing the status code,
  2. setting a listener for exceptions thrown from the controllers,
  3. checking the instance of the exception object (to tell it apart from all the "unexpected" exceptions),
  4. setting the status code in that listener, possibly short-circuiting the event loop as well.

Hope that'll get you on the right track.

For reference see:

I ended up checking on bootstrap event which controller is requested and if it is necessary, detaching notfoundstrategy.

Here you can find my solution to this problem: http://www.cagataygurturk.com/zf2-controller-specific-not-found-page/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM