有时异常处理有效,有时则无效。我将尝试只显示最少量的相关代码:
应用程序/graphql/dbz_schema.rb:
DbzSchema = GraphQL::Schema.define do
mutation(Types::MutationType)
query(Types::QueryType)
end
应用程序/graphql/types/breed_type.rb:
Types::BreedType = GraphQL::ObjectType.define do
name "Breed"
field :id, !types.ID
field :name, !types.String
end
应用程序/graphql/types/mutation_type.rb:
Types::MutationType = GraphQL::ObjectType.define do
name "Mutation"
field :updateBreed, function: Resolvers::UpdateBreed.new
end
应用程序/graphql/resolvers/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()
});
}