Respond with a nice 400 if we cannot parse the JSON request

pull/2275/head
Hagen Schink 10 years ago
parent 8922eb3040
commit 0fb2ccfa2a
  1. 46
      lib/api/errors/parse_error.rb
  2. 13
      lib/api/root.rb

@ -0,0 +1,46 @@
#-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
module API
module Errors
class ParseError < InvalidRequestBody
def initialize(message)
super 'The request body was neither empty, nor did it contain a single JSON object.'
@details = { parseError: clean_parse_error(message) }
end
private
def clean_parse_error(message)
message.gsub(/\s?\[parse.c\:\d+\]/, '')
end
end
end
end

@ -41,11 +41,24 @@ module API
end
end
class Parser
def call(object, _env)
MultiJson.load(object)
rescue MultiJson::ParseError => e
error = ::API::Errors::ParseError.new(e.message)
representer = ::API::V3::Errors::ErrorRepresenter.new(error)
throw :error, status: 400, message: representer.to_json
end
end
content_type 'hal+json', 'application/hal+json; charset=utf-8'
content_type :json, 'application/json; charset=utf-8'
format 'hal+json'
formatter 'hal+json', Formatter.new
parser :json, Parser.new
helpers do
def current_user
return User.current if Rails.env.test?

Loading…
Cancel
Save