-
Notifications
You must be signed in to change notification settings - Fork 8
Errors Handling
This page is up to date for Rango 0.1.
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.
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
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
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
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
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
class XmlHTTP404 < HTTP404
CONTENT_TYPE ||= "text/xml"
def message
"<error>#{super}</error>"
end
end
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