diff --git a/lib/better_errors/middleware.rb b/lib/better_errors/middleware.rb index f84f7015..1bba6402 100644 --- a/lib/better_errors/middleware.rb +++ b/lib/better_errors/middleware.rb @@ -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 - "
No errors have been recorded yet.
Better Errors v#{BetterErrors::VERSION}
"
+ [ '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
@@ -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
+ "No errors have been recorded yet.
Better Errors v#{BetterErrors::VERSION}
"
+ end
end
end
diff --git a/spec/better_errors/middleware_spec.rb b/spec/better_errors/middleware_spec.rb
index e538442f..c8106fdb 100644
--- a/spec/better_errors/middleware_spec.rb
+++ b/spec/better_errors/middleware_spec.rb
@@ -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