Wednesday, August 28, 2013

Re: Throwing error should output JSON

Replying to myself - this is what I found.

The presentation that I saw that said that putting error400.ctp in a json folder under /app/View/Errors would work automatically seems to be incorrect.

The solution I came up with included the following steps:
1. Set a flag in app/Controller/AppController indicating that this is a REST call. As there does not seem to be an is("rest") or isRest call I did this based on the extension.
In AppController.php within the AppController class add:
  public $REST = FALSE;

  function beforeFilter()
  {
    // Add additional checks here to support other formats
    if (isset($this->request->params['ext']) && ($this->request->params['ext'] == 'json'))
    {
      $this->REST = 'json';
    }
    $this->set('REST', $this->REST);
  }

2. Using the comments from COTP that I found here I copied CakeErrorController.php into my app/Controller folder and added a beforeRender method:
  public function beforeRender()
  {
    parent::beforeRender();
    // If this is a REST call then use the views for that format type
    if ($this->REST)
    {
      $this->viewPath = "Errors/" . $this->REST;
      // The documentation says to set the layout in the view files but it seems
      // more efficient to put it here once then in all of the view files
      // Use a different layout if you want something special. ajax layout just
      // outputs the view content with nothing else
      $this->layout = 'ajax';
    }
  }
 
3. Now I can create View/Errors/json/error400.ctp:
{"Error":
  {
    "code": <?php $Code = $error->getCode(); echo $Code; ?>,
    "description": "<?php $Status = $this->response->httpCodes($Code); echo $Status[$Code] . ": " . $error->getMessage(); ?>"
  }
}

Hope this helps someone

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.

No comments: