Skip to content

Commit

Permalink
add error handling for .txt + .json formats
Browse files Browse the repository at this point in the history
  • Loading branch information
rococodogs committed Nov 11, 2019
1 parent 002eb59 commit 89b7179
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
18 changes: 17 additions & 1 deletion app/controllers/error_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ class ErrorController < ApplicationController
respond_to :html

def show
render @status.to_s, status: @status.to_i
respond_to do |format|
format.html { render @status.to_s, status: @status.to_i }
format.json { render json: json_response, status: @status.to_i }
format.text { render plain: plain_text_response, status: @status.to_i }
end
rescue
send_honeybadger_notification!

Expand All @@ -15,6 +19,18 @@ def show

private

def json_response
%({"error": true, "status": #{@status.to_i}, "message": "#{status_message}"})
end

def plain_text_response
"#{@status} #{status_message}"
end

def status_message
Rack::Utils::HTTP_STATUS_CODES.fetch(@status, '')
end

def send_honeybadger_notification!
Honeybadger.notify(
'An error occurred causing a 500 page to render',
Expand Down
26 changes: 26 additions & 0 deletions spec/features/error_page_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,32 @@
expect(response).to have_http_status(:not_found)
expect(response.body).to include 'The page you requested could not be found.'
end

context '.txt' do
it 'renders the error in plain text' do
without_detailed_exceptions do
get '/this/does/not/exist.txt'
end

expect(response).to have_http_status(:not_found)
expect(response.body).to eq '404 Not Found'
end
end

context '.json' do
let(:json_response) do
%({"error": true, "status": 404, "message": "Not Found"})
end

it 'renders the error as json' do
without_detailed_exceptions do
get '/this/does/not/exist.json'
end

expect(response).to have_http_status(:not_found)
expect(response.body).to eq json_response
end
end
end

describe '500 (catch-all)' do
Expand Down

0 comments on commit 89b7179

Please sign in to comment.