On Wed, Jun 5, 2013 at 12:20 PM, pobrejuanito <[email protected]> wrote:
> I am currently in the process of building an API with ZF2 2.1 and I've
> downloaded the Skeleton Application and built my module named /API/. I am
> trying to figure out the best way to return 404 JSON response and routes
> don't match and catch fatal errors and exceptions and respond with
> appropriate JSON response.
>
> Currently in my module directory I have /Application/ and /API/ modules.
> The /API/ module is where my config and source is for my app.
>
> In my /module/API/config/module.config.php I have the JsonViewStrategy
> configured and returning JSON responses for requests
>
> 'view_manager' => array(
> 'strategies' => array(
> 'ViewJsonStrategy'
> ),
> ),
Enabling the ViewJsonStrategy does not mean responses will be
automatically returned as JSON. What it means is that if you return a
JsonModel from your controller, the JsonStrategy will intercept it and
return JSON.
So, to make it work, you have several options:
- Explicitly return a JsonModel from your controller
- Use the AcceptableViewModelSelector plugin within your controller to
auto-select an appropriate view model type based on the Accept header.
You can then tell the plugin which Accept types should map to a
JsonModel.
- Via a listener, re-cast a view model to a JsonModel and re-set it in
the MvcEvent. (I'd steer away from this, actually.)
<snip>
> What are some ways I can "map" the exception and 404 so that I can generate
> a JSON response?
Now, for this, you need to do something different. Register a listener
on the dispatch.error event, and re-cast the view model it injects
into the MvcEvent to a JsonModel, or register your listener earlier,
create an appropriate view model, stop propagation, and return. As an
example, try the following in a module class somewhere:
namespace SomeModule;
use Zend\View\Model\JsonModel;
class Module
{
public function onBootstrap($e)
{
$events = $e->getTarget()->getEventManager();
$events->attach('dispatch.error', array($this,
'onDispatchError'), 100);
}
public function onDispatchError($e)
{
$error = $e->getError();
if (!$error) {
// No error? nothing to do.
return;
}
$request = $e->getRequest();
$headers = $request->getHeaders();
if (!$headers->has('Accept')) {
// nothing to do; can't determine what we can accept
return;
}
$accept = $headers->get('Accept');
if (!$accept->match('application/json')) {
// nothing to do; does not match JSON
return;
}
$model = new JsonModel();
// inject as needed with error/exception information.
// maybe set HTTP response codes based on type of error.
// etc.
$e->setResult($model);
$e->stopPropagation();
return $model;
}
}
--
Matthew Weier O'Phinney
Project Lead | [email protected]
Zend Framework | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc
--
List: [email protected]
Info: http://framework.zend.com/archives
Unsubscribe: [email protected]