Skip to content

Commit

Permalink
Merge pull request AlchemyCMS#2071 from tvdeyen/handle-json-requests-…
Browse files Browse the repository at this point in the history
…in-error-handler

Handle json requests in error handler
  • Loading branch information
tvdeyen authored Apr 17, 2021
2 parents 065a7ae + 7796ea1 commit ed99394
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
5 changes: 4 additions & 1 deletion app/controllers/alchemy/admin/base_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ def show_error_notice(error)
if request.xhr?
render action: "error_notice"
else
render "500", status: 500
respond_to do |format|
format.html { render "500", status: 500 }
format.json { render json: { message: @notice }, status: 500 }
end
end
end

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/alchemy/api/elements_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def index
if params[:named].present?
@elements = @elements.named(params[:named])
end
@elements = @elements.includes(*element_includes)
@elements = @elements.includes(*element_includes).order(:position)

render json: @elements, adapter: :json, root: "elements"
end
Expand Down
33 changes: 31 additions & 2 deletions spec/controllers/alchemy/admin/base_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
before do
allow(I18n).to receive(:default_locale) { :es }
allow(I18n).to receive(:available_locales) { [:es] }
allow(controller).to receive(:session) { { alchemy_locale: "kl"} }
allow(controller).to receive(:session) { { alchemy_locale: "kl" } }
end

it "sets I18n.locale to the default locale" do
Expand Down Expand Up @@ -60,7 +60,7 @@
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") }
let(:user) { create(:alchemy_dummy_user, :as_admin) }
let(:user) { create(:alchemy_dummy_user, :as_admin) }

context "and she has locked pages" do
before do
Expand All @@ -76,4 +76,33 @@
end
end
end

describe "error responses" do
controller do
def index
raise "Error!"
end
end

before do
allow_any_instance_of(described_class).to receive(:raise_exception?) { false }
end

context "for HTML requests" do
it "renders 500 template" do
get :index
expect(response).to render_template("alchemy/base/500")
end
end

context "for JSON requests" do
render_views

it "renders 500 template" do
get :index, format: :json
expect(response.media_type).to eq("application/json")
expect(JSON.parse(response.body)).to eq({ "message" => "Error!" })
end
end
end
end

0 comments on commit ed99394

Please sign in to comment.