Reputation: 1475
I am attempting to provide user friendly error messages via my web application for certain errors. I want to be able to pass the throw exception call and extra paramter, such like "USER" so the error controller gives this paramter to the view and displays a different style page with maybe a more friendly color and a meaningful message, but I can't figure out how to pass extra arguments. Here is the current setup:
Some check in one of the controllers:
throw new Zend_Controller_Exception("User not found",403);
Error controller (ErrorController.php):
class ErrorController
extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
etc.
So I want to be able to do like:
$this->view->type = $this->_getParam('type');
in the controller, so I can do this in the view:
if($this->type == "USER") {
some css stuff
echo $this->exception;
Upvotes: 0
Views: 412
Reputation: 14184
Sounds like you could:
Create a custom exception class (My_Exception_UserFriendly
or the like) that accepts your other parameters
In a controller (or elsewhere) throw this exception with your custom params, and
Use an instanceof
check in your ErrorController
to populate your view variables.
And, as you already note, make sure your view checks for the presence of that user-friendly data before attempting to render it.
Update
Actually, reading more closely, it doesn't look like you need the exception to carry any additional information. Simple creating a custom class should be sufficient for your detection/rendering purposes.
You can create an empty (!) exception class in library/My/Exception/UserFiendly.php
:
class My_Exception_UserFriendly extends Exception
{
}
Then when you encounter an error that you would like to show to the user in a friendly way, just throw an exception of this type:
if ($rainyDay){
throw new My_Exception_UserFriendly('Seeing some inclement weather, I\'m afraid');
}
Then in your ErrorController::errorAction()
:
$exception = $this->_getParam('error_handler')->exception;
if ($exception instanceof My_Exception_UserFriendly){
$this->view->friendlyErrorMessage = $exception->getMessage();
}
Finally, down in your view-script error/error.phtml
:
<?php if ($this->friendlyErrorMessage): ?>
<h2>With Humble Apologies, Valued User</h2>
<p><?= $this->escape($this->friendlyErrorMessage) ?></p>
<?php endif; ?>
In fact, some would argue that the specific message we render is purely a view consideration. In that case, you could create a custom exception - perhaps extending this generic UserFriendly
exception - for each friendly message you wish to support. Then in your ErrorController
, detect the specific sub-type and set a key in the view identifying that subtype. Then, in the view, render the specific friendly message corresponding to the given key. Might be overkill just for the sake of purity, but throwing it out there for those who value those considerations.
Upvotes: 4