3.4 Adding an Error Page
We’ve now created all the features we need. In this section, we’ll create an error page for debugging purposes.
So far, we have an error_page
method that returns an “oops” string when an error happens.
Take a look at the do_GET
method. This method receives req
, builds a page, and calls the error_page
error when exceptions are raised.
def do_GET(req, res) |
|
do_request(req, res) |
|
build_page(req, res) |
|
rescue |
|
error_page(req, res) |
|
end |
The current error_page
method simply returns “oops,” as shown in the following code. To actually see the error page, stop your ReminderCGI
server, and browse the page.
def error_page(req, res) |
|
res["content-type"] = "text/plain" |
|
res.body = 'oops' |
|
end |
When actually running a site, the site should redirect to a static error page or say something better than “oops.”
Let’s modify error_page
and display debugging error messages. Some web servers may write the error into error logs.
We’ll make an error display class to help you debug. It will display error pages like those you see when you run Ruby on the Web.
class ErrorView |
|
include ERB::Util |
|
|
|
def self.create_erb |
|
ERB.new(<<EOS) |
|
<html><head><title>error</title></head> |
|
<body> |
|
<p><%=h error %> - <%=h error.class %></p> |
|
<ul> |
|
<% info.each do |line| %> |
|
<li><%=h line %></li> |
|
<% end %> |
|
</ul> |
|
</body> |
|
</html> |
|
EOS |
|
end |
|
|
|
extend ERB::DefMethod |
|
def_erb_method('to_html(req, res, error=$!, info=$@)', create_erb) |
|
end |
ErrorView
converts exception information ($!, $@), which you receive when rescue
is raised, and turns it into HTML.
Change error_page
to return the result of ErrorView#to_html
, instead of “oops.”
def error_page(req, res) |
|
res["content-type"] = "text/html; charset=utf-8" |
|
res.body = ErrorView.new.to_html(req, res) |
|
end |
It should now display where the DRb::DRbConnError
exception was raised.