Looking at the source code, it looks like httpresponse.rb
has a "hook" called create_error_page
:
if respond_to?(:create_error_page)
create_error_page()
return
end
So, if you add your own Ruby method called create_error_page
in WEBrick::HTTPResponse
, you can set your own markup:
module WEBrick
class HTTPResponse
def create_error_page
@body = ''
@body << <<-_end_of_html_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
<BODY>
<H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
<HR>
<P>Custom error page!</P>
</BODY>
</HTML>
_end_of_html_
end
end
end
Note that you have access to variables like @reason_phrase
and ex.code
. In your case, you can use ex.code
(eg: 401
) to set different content if you wish.
Here is a full example that you can run in an irb
console that displays a custom error page (note that it assumes you have a directory called Public
in your file system):
require 'webrick'
module WEBrick
class HTTPResponse
def create_error_page
@body = ''
@body << <<-_end_of_html_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
<BODY>
<H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
<HR>
<P>Custom error page!</P>
</BODY>
</HTML>
_end_of_html_
end
end
end
root = File.expand_path '~/Public'
server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => root
trap 'INT' do server.shutdown end
server.start
When you go to http://localhost:8000/bogus
(a page that does not exist), you should see the custom error page, like so:
Hope it helps! :-]