Graphql异常处理没有捕获异常

时间:2017-11-03 12:04:12

标签: ruby-on-rails ruby graphql graphql-ruby

有时异常处理有效,有时则不然。我将尝试仅显示最少量的相关代码:

应用程序/ graphql / dbz_schema.rb:

DbzSchema = GraphQL::Schema.define do
  mutation(Types::MutationType)
  query(Types::QueryType)
end

应用程序/ graphql /类型/ breed_type.rb:

Types::BreedType = GraphQL::ObjectType.define do
  name "Breed"
  field :id, !types.ID
  field :name, !types.String
end

应用程序/ graphql /类型/ mutation_type.rb:

Types::MutationType = GraphQL::ObjectType.define do
  name "Mutation"

  field :updateBreed, function: Resolvers::UpdateBreed.new
end

应用程序/ graphql /解析器/ update_breed.rb

class Resolvers::UpdateBreed < GraphQL::Function
  argument :name, !types.String
  argument :id, !types.ID

  type Types::BreedType

  def call(_obj, args, _ctx)
    Breed.update(args[:id], { name: args[:name] })

  rescue ActiveRecord::RecordNotFound => e
    GraphQL::ExecutionError.new("Invalid input: #{e.record.errors.full_messages.join(', ')}")
  end
end

如果我运行查询:

mutation {
  updateBreed(id: 7, name: "Cat") {
    id
    name
  }
}

我得到SyntaxError: Unexpected token < in JSON at position 0

但服务器日志显示:

Started POST "/graphql" for 127.0.0.1 at 2017-11-03 12:02:03 +0000
Processing by GraphqlController#execute as */*
  Parameters: {"query"=>"mutation {\n  updateBreed(id: 7, name: \"Cat\") {\n    id\n    name\n  }\n}", "variables"=>nil}}
  Breed Load (0.2ms)  SELECT  "breeds".* FROM "breeds" WHERE "breeds"."id" = $1 LIMIT $2  [["id", 7], ["LIMIT", 1]]
Completed 500 Internal Server Error in 33ms (ActiveRecord: 3.7ms)



ActiveRecord::RecordNotFound (Couldn't find Breed with 'id'=7):

app/graphql/resolvers/update_breed.rb:8:in `call'
app/controllers/graphql_controller.rb:10:in `execute'

这清楚地显示了一个ActiveRecord::RecordNotFound,我试图拯救它,但它没有用。

Chrome控制台显示:

graphql Failed to load resource: the server responded with a status of 404 (Not Found) POST http://localhost:3000/graphql 404 (Not Found)

它指向以下graphql javascript,突出显示以return开头的第二行:

    function graphQLFetcher(graphQLParams) {
      return fetch(graphQLEndpoint, {
        method: 'post',
        headers: {
  "Content-Type": "application/json",
  "X-CSRF-Token": "SWM3i9waP9i/sUMo1vcCg/9wdDRmPfkd99uuAKrIAEdz522ir1ildIccLpSDKhYE76cZgimk3IW5sXkOd0d3rQ=="
},
        body: JSON.stringify(graphQLParams),
        credentials: 'include',
      }).then(function (response) {
        return response.json()
      });
    }

1 个答案:

答案 0 :(得分:0)

我一直在尝试实现相同的目标,并尽可能减少对默认值的干扰。我还想避免捕获异常,因为我的代码随后负责适当地处理它们:-)

相反,我发现您可以将路由转换为JSON端点,因此它将响应转换为JSON-包括异常和错误:

例如,在我的routes.rb中:

  post '/graphql', to: 'graphql#execute', defaults: { format: :json }

现在这会导致JSON(而不是HTML)中的GraphQL请求响应中断:

{"status":500,"error":"Internal Server Error"}