Skip to content

Commit

Permalink
Handle json requests in show_error_notice
Browse files Browse the repository at this point in the history
If the request is a accepts json we need to return
the error message as json.
  • Loading branch information
tvdeyen authored and sascha-karnatz committed Dec 14, 2023
1 parent 504f5d1 commit 85cbdf9
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 6 deletions.
11 changes: 5 additions & 6 deletions app/controllers/alchemy/admin/base_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,13 @@ def show_error_notice(error)
@error = error
# truncate the message, because very long error messages (i.e from mysql2) causes cookie overflow errors
@notice = error.message[0..255]
@trace = error.backtrace[0..50]
if request.xhr?
if request.format.json?
render json: {message: @notice}, status: 500
elsif request.xhr?
render action: "error_notice"
else
respond_to do |format|
format.html { render "500", status: 500 }
format.json { render json: {message: @notice}, status: 500 }
end
@trace = error.backtrace[0..50]
render "500", status: 500
end
end

Expand Down
57 changes: 57 additions & 0 deletions spec/controllers/alchemy/admin/base_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,63 @@
end
end

describe "#show_error_notice" do
let(:error) do
ActiveRecord::ActiveRecordError.new("Database is busy")
end

subject do
controller.send(:show_error_notice, error)
end

before do
allow(controller).to receive(:render)
end

context "for a json request" do
before do
expect(controller).to receive(:request) do
double(format: double(json?: true))
end
end

it "returns error message" do
subject
expect(controller).to have_received(:render).with(
json: {message: "Database is busy"},
status: 500
)
end
end

context "for a xhr request" do
before do
expect(controller).to receive(:request) do
double(xhr?: true, format: double(json?: false))
end.twice
end

it "renders error notice" do
subject
expect(controller).to have_received(:render).with(action: "error_notice")
end
end

context "for a html request" do
before do
expect(controller).to receive(:request) do
double(xhr?: false, format: double(json?: false))
end.twice
error.set_backtrace(%(foo))
end

it "renders error template" do
subject
expect(controller).to have_received(:render).with("500", status: 500)
end
end
end

context "when current_alchemy_user is present" do
let!(:page_1) { create(:alchemy_page, name: "Page 1") }
let!(:page_2) { create(:alchemy_page, name: "Page 2") }
Expand Down

0 comments on commit 85cbdf9

Please sign in to comment.