Skip to content

Commit

Permalink
Serve the text-only page for non-graphical browsers. See #79.
Browse files Browse the repository at this point in the history
  • Loading branch information
rstacruz committed Jan 17, 2013
1 parent f6ac808 commit ebab4fa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
24 changes: 18 additions & 6 deletions lib/better_errors/middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,25 @@ def protected_app_call(env)
log_exception
show_error_page(env)
end

def show_error_page(env)
content = if @error_page
@error_page.render
type, content = if @error_page
if text?(env)
[ 'plain', @error_page.render('text') ]
else
[ 'html', @error_page.render ]
end
else
"<h1>No errors</h1><p>No errors have been recorded yet.</p><hr>" +
"<code>Better Errors v#{BetterErrors::VERSION}</code>"
[ 'html', no_errors_page ]
end

[500, { "Content-Type" => "text/html; charset=utf-8" }, [content]]
[500, { "Content-Type" => "text/#{type}; charset=utf-8" }, [content]]
end

def text?(env)
env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" ||
!env["HTTP_ACCEPT"].to_s.include?('html')
end

def log_exception
return unless BetterErrors.logger
Expand All @@ -106,5 +113,10 @@ def internal_call(env, opts)
response = @error_page.send("do_#{opts[:method]}", JSON.parse(env["rack.input"].read))
[200, { "Content-Type" => "text/plain; charset=utf-8" }, [JSON.dump(response)]]
end

def no_errors_page
"<h1>No errors</h1><p>No errors have been recorded yet.</p><hr>" +
"<code>Better Errors v#{BetterErrors::VERSION}</code>"
end
end
end
15 changes: 14 additions & 1 deletion spec/better_errors/middleware_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,20 @@ module BetterErrors
it "should return UTF-8 error pages" do
status, headers, body = app.call({})

headers["Content-Type"].should == "text/html; charset=utf-8"
headers["Content-Type"].should match /charset=utf-8/
end

it "should return text pages by default" do
status, headers, body = app.call({})

headers["Content-Type"].should match /text\/plain/
end

it "should return HTML pages by default" do
# Chrome's 'Accept' header looks similar this.
status, headers, body = app.call("HTTP_ACCEPT" => "text/html,application/xhtml+xml;q=0.9,*/*")

headers["Content-Type"].should match /text\/html/
end

it "should log the exception" do
Expand Down

0 comments on commit ebab4fa

Please sign in to comment.