Skip to content
This repository was archived by the owner on Feb 7, 2020. It is now read-only.

Errors Handling

botanicus edited this page Sep 13, 2010 · 24 revisions

This page is up to date for Rango 0.1.

Introduction

There is a lot of ways how you can handle exceptions in MVC pattern. In Merb you have special Exceptions controller, Rails prefer to keep it in one controller, or you can require more complex setup … so Rango just let you set it up easily.

Internal Implementation

All classes derivated from Rango::HttpError can be converted into Rack response (see Rango::HttpError#to_response).

- Exceptions classes in Rango
- List of HTTP Status Codes

Default Exceptions Handling

class Posts < Rango::Controller
  def index
    @post = Post.get(params[:id])
    raise NotFound, "Post with given ID doesn't exist" unless @post
    render "posts.html"
  end
end

Rails-like Exceptions Handling

Well, not exactly the same syntax, but definitely the same concept:

class Application < Rango::Controller
  def rescue_http_error(exception)
    self.send(exception.to_snakecase)
  end
end

class Posts < Application
  def index
    @post = Post.get(params[:id])
    raise NotFound
    render "posts.html"
  end

  def not_found
    render "posts/not_found"
  end
end

Merb-like Exceptions Handling

class Application < Rango::Controller
  def rescue_http_error(exception)
    method_name = exception.to_snakecase
    Exceptions.route_to(method_name)
  end
end
class Exceptions < Rango::Controller
  def not_found
  end

  def rescue_http_error(exception)
   # TODO: what it should do?
    method_name = exception.to_snakecase
    Exceptions.route_to(method_name)
  end
end

Automatic Template Rendering for Proper Error

This solution will automatically render errors/not_found if you raise NotFound error, errors/internal_server_error if you raise InternalServerError error etc.

class Application < Rango::Controller
  def rescue_http_error(exception)
    basename = exception.to_snakecase
    render "errors/#{basename}"
  rescue TemplateError
    render "errors/generic"
  end
end

Custom Exceptions Classes

class XmlHTTP404 < HTTP404
  CONTENT_TYPE ||= "text/xml"
  def message
    "<error>#{super}</error>"
  end
end

HTTP Exceptions Outside of Controllers

As you know, in Rango you aren’t limited on controllers or whatever. Lets take a look how you can implement default exceptions handling from controllers for you custom application:

lambda do |env|
  begin
    # code of your app
  rescue Rango::HttpError => exception
    exception.to_response
  end
end

And here we are! Or, in similar way as above, you can use render "errors/#{exception.to_snakecase}" or whatever you want.

http://gist.github.com/180878

def rescue_http_error(exception)
  case exception.status
  when 404
    redirect ObsoleteUrl.find(request.path_info).new_location
  end
end

Clone this wiki locally