I’m quite new to Elixir and Absinthe and I’m stuck trying to create a middleware to handle any kind of error when querying or mutating data.
For instance, I’m trying to query a User by id which I know doesn’t exist and I get the following (expected) error on the server and in the client:
(Ecto.NoResultsError) expected at least one result but got none in query
Is there any example to format the error so it shows something like this in the client:
{
error: {
code: 404,
message: 'User not found',
}
}
1 Like
Seems like you are using Ecto.Repo.get!/3 which throws the Ecto.NoResultsError
exception without giving you a chance to react.
You should instead use Ecto.Repo.get/3 (note the lack of !
at the end) which returns either {:ok, record}
or {:error, reason}
, with the latter giving you a chance to return a HTTP 404 from your resolver.
3 Likes
Please, a question. If there’s no time to react then why is this method present on the Repo? What’s its function exactly? You are right, I had the same problem and it fixed with what you proposed.
Hello and welcome,
it’s not as if You have no time to react, You just want to fail in case it’s not ok… like in the seed file.
1 Like
oh, I see. what you are saying is that with Repo.get!/3 the program will stop functioning ( will end ) in case of errors? And in the case of Repo.get/3 the program will continue working but it will return you a failing HTTP response?
Yes 
But You still can recover from an Exception with rescue.
1 Like
Thank you very much for your response and clarification. I’ve needing an answer to that weeks ago 
The bang functions (those ending with !
) usually throw an exception which can interrupt the program, yes.
The non-bang functions usually return tuples – {:ok, result}
and {:error, details}
.
It’s a good practice for library authors to provide both so people can make the call for themselves on which style do they want their program in.
2 Likes