Skip to content
This repository has been archived by the owner on Jun 21, 2022. It is now read-only.

Commit

Permalink
Added AppError middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ixti committed Sep 4, 2011
1 parent a336423 commit ff28d55
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
3 changes: 3 additions & 0 deletions config.ru
Expand Up @@ -28,6 +28,9 @@ end
# show exceptions when not-production # show exceptions when not-production
unless 'production' == ENV['RACK_ENV'] unless 'production' == ENV['RACK_ENV']
use Rack::ShowExceptions use Rack::ShowExceptions
else
require './lib/rack/app_error'
use Rack::AppError, :file => 'public/500.html'
end end




Expand Down
64 changes: 64 additions & 0 deletions lib/rack/app_error.rb
@@ -0,0 +1,64 @@
# blog.ixti.ru, private scratchpad with public access
#
# Copyright (c) 2011 Aleksey V Zapparov AKA ixti <ixti@member.fsf.org>
#
# blog.ixti.ru is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# blog.ixti.ru is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with blog.ixti.ru. If not, see <http://www.gnu.org/licenses/>.


module Rack
class AppError
def initialize(app, options={})
@app = app
@file = options[:file]
end

def call(env)
@app.call(env)
rescue StandardError, LoadError, SyntaxError => e
env["rack.errors"].puts(dump_exception e)
env["rack.errors"].flush

if prefers_plain_text?(env)
content_type = "text/plain"
body = "Application Error\n"
else
content_type = "text/html"
body = ::IO.readlines @file
end

[
500,
{
"Content-Type" => content_type,
"Content-Length" => Rack::Utils.bytesize(body.join).to_s
},
body
]
end

protected

def prefers_plain_text?(env)
env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" && (!env["HTTP_ACCEPT"] || !env["HTTP_ACCEPT"].include?("text/html"))
end

def dump_exception(exception)
string = "#{exception.class}: #{exception.message}\n"
string << exception.backtrace.map { |l| "\t#{l}" }.join("\n")
string
end
end
end

# vim:ts=2:sw=2

0 comments on commit ff28d55

Please sign in to comment.