React-Apollo Error Only Shows Status Code 500
I Am Wondering How I Can Access My Throw Errors in My Frontend with React-Apollo? My Simple Resolver for Fetching a Single Customer Is Like This, Where Args...
I am wondering how I can access my throw errors in my frontend with react-apollo?
My simple resolver for fetching a single customer is like this, where args._id is the customer ID. Now if the id is not valid react-apollo just throws an 500 error.
Error! Network error: Response not successful: Received status code 500
customer: async (args, req) => {
const validateId = (id) => {
return mongoose.Types.ObjectId.isValid(id)
}
if(args._id && validateId(args._id)){
try {
const customer = await Customer
.findById(args._id)
return transformCustomer(customer)
}
catch (err) {
throw err
}
}
else {
throw new Error("error")
}
},
I tried using errorPolicy="all" and accessing error.graphQLErrors, but that dosn't work, because it throws a 500 error.
Cannot read property 'graphQLErrors' of undefined
2 Answers
EDIT (in addiition to wrapping in a try/catch) - Perhaps you should be checking whether _id is valid before sending a request to the server:
customer: async (args, req) => {
// do some validation on _id
if (args._id && isValid(args._id) ) {
try {
const customer = await Customer.findById(args._id)
} catch (e) {
// handle server error
}
} else {
// handle invalid _id here
}
To catch an error thrown by apollo you need to wrap the call that executes the query into a try-catch.
In your example this is probably:
try {
const customer = await Customer.findById(args._id);
} catch(err) {
// handle the error
}
However a 500 is always a programming error and should be fixed on the server. It seems your server doesn't do the required validation before using the parameters passed in the query.