CakePHP 2.x: How to return 404 HTTP status code when missing view
Introduction
By default, CakePHP 2.x returns 500 status code when missing view. This is because of View#_getViewFileName()
throws MissingViewException
in such a case.
Ref: https://github.com/cakephp/cakephp/blob/2.x/lib/Cake/View/View.php#L1031
This post will show one examples of how to return 404 status code.
Codes
So, you will need do the following.
- Create new
MyView
class which is subclass ofView
class. It throwsNotFoundException
- Modify your controller to use
MyView
class instead ofView
class
1. Create new MyView class
View/MyView.php
<?php
App::uses('View', 'View');
class MyView extends View {
public function _getViewFileName($name = null) {
try {
return parent::_getViewFileName($name);
} catch (MissingViewException $e) {
throw new NotFoundException();
}
}
}
2. Modify your controller to use MyView class
Controller/FoosController.php
<?php
App::uses('AppController', 'Controller');
class FoosController extends AppController {
public function bar() {
$this->viewClass = 'My';
// Do something
}
}