Ramaze Error Handling

I recently had to build custom 404 & exception handlers for a Ramaze application. There are several useful discussions on the Ramaze Google Group regarding this topic but I thought I’d synthesize the solution here for the sake of convenience.

Handling 404 Errors

Ramaze has a built-in controller action to handle 404 errors; it presents a vanilla page stating ‘No action found at: /xyz‘. Overriding this action is easy and well documented but there are a couple of things that might want to consider.

First, if you would like all 404 errors across your application to be handled by a single action, you will need to add your handling code to the base controller.

Second, using a view file corresponding to the controller action does not quite work. While the view is correctly rendered when the 404 occurs directly under a path mapped to the 404 handler’s controller (eg. /my_missing_action) it is not rendered for 404 errors occurring under paths mapped to other controllers (eg. /users/my_missing_action).

A workaround for this is to use the render_file method to manually render a view you’ve created. I have not done due diligence on this problem so I cannot tell you why it occurs – maybe it is a bug or maybe (likely) I’m missing something. If anyone has an explanation or a better work around I’d love to hear it.

Source for a Custom 404 Handler

Handling Exceptions

Routing Exceptions

Ramaze also has a built-in exception handler which presents a developer-friendly stack trace (one which I’m sure you will want to hide for the end-users). The Ramaze Google Group discussions here and here talk about how to override this default handler. It boils down to using Rack::RouteExceptions.route(exception, to); a method that takes the type of exception to route and the path of the action to route it to.

For example, to route all exceptions to the same controller you could use (as stated by Lars Olsson here):

Rack::RouteExceptions.route(Exception, MyController.r(:error))

Alternatively, to handle all IOError exceptions separately you could use:

Rack::RouteExceptions.route(IOError, MyController.r(:io_error))
Rack::RouteExceptions.route(Exception, MyController.r(:error))

Note the order of the calls to route is important. You must route the most specific exceptions first or they will be routed to more general handlers specified before them.

Unlike the 404 error handler, using a standard view file does work here.

The Exception Object

To obtain the exception object within the controller action you can call:

@error = request.env[Rack::RouteExceptions::EXCEPTION]

Source for a Custom Exception Handler

  • Dreinavarro

    How are you setting the response error code?

  • Dreinavarro

    just realized you are just routing all caught errors to your controller, so you don’t need to set the response code.

    u know how to do that though?

blog comments powered by Disqus