Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

Basically, I'm trying to emulate show_error from EE/CI: http://ellislab.com/codeigniter/user-guide/general/errors.html

I want to just use the generic Craft error template (/craft/app/templates/error.html), like what happens if you have a DB connection error, and have it serve a 500.

This is from with a plugin controller.

What's the best way to do that?

share|improve this question

3 Answers 3

up vote 4 down vote accepted

I'm not familiar with EE's show_error, but a plugin's error template logic is identical to the logic that Craft uses to determine what to display.

From your plugin, if you:

throw new HttpException($statusCode, $optionalMessage)

Where $statusCode is 404 or 400, or any proper http status code, Craft will load the corresponding 404.html, 400.html, etc. from the craft/app/templates folder displaying the optional message, or the more generic message supplied in the template if no optional one is provided.

However, if you have supplied your own 404, 400, etc. from your own craft/templates folder, Craft will display that one instead of the one it provides so you can customize these errors for your site.

If you:

throw new Exception($optionalMessage)

while devMode is enabled, then Craft will load exception.html which will display the full error long with stack trace to help in debugging. If devMode is not enabled, it will display the more generic error.html.

Craft specifically checks for database connection errors and will display the error.html template while setting a 500 status code.

share|improve this answer

Craft itself (I'm referencing the EntriesController) checks to see if an entry is saved. If it doesn't it, points back to the template and hands it an error message in the session and any needed variables.

In the case of your plugin, gather your form data and errors and send it back. Craft does it all in a single Model. You can do the same or different. It doesn't matter so long as those using the plugin knows what's up.

Example based on a Craft Controller (with optional Ajax response):

if (craft()->request->isAjaxRequest())
{
    $this->returnJson(array(
        'errors' => $errors,
    ));
}
else
{
    $userSessionService->setError(Craft::t('Error Message!'));

    // Send the data back to the template.
    craft()->urlManager->setRouteVariables(array(
        'data' => $data,
        'errors' => $errors,
    ));
}
share|improve this answer

This will do it, and you can change the 400 to whatever type of http error you want:

throw new HttpException(400, 'Error message text');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.