diff --git a/lib/api/errors/parse_error.rb b/lib/api/errors/parse_error.rb new file mode 100644 index 0000000000..7cc08ca4b0 --- /dev/null +++ b/lib/api/errors/parse_error.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 diff --git a/lib/api/root.rb b/lib/api/root.rb index acda65ff3c..0c470ffcde 100644 --- a/lib/api/root.rb +++ b/lib/api/root.rb @@ -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?