question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Return custom error message

See original GitHub issue

Hi there!

I’d like to know the better way to raise an exception on a Mutation. For example, while trying to create a User with an email address that already exists.

if email
    user = User.objects.filter(email=email).first()

    if user:
       # ?

return CreateUser(username=username, password=password)

I know that I can raise Exception('message'), but is this the best way? Can we do it differently?

Thanks!

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:7
  • Comments:14 (2 by maintainers)

github_iconTop GitHub Comments

46reactions
ariannedeecommented, Aug 16, 2017

I usually return a GraphQLError.

from graphql import GraphQLError
...
raise GraphQLError('That email already exists')

It takes a few more arguments: nodes, stack, source, and positions, but I have never used these.

45reactions
jkimbocommented, Mar 17, 2018

I’m going to close this issue since it’s stale. However just to add: I’ve found that modeling expected errors as part of your mutation response is essential. Your client needs to know what to do if your mutation fails. To do that I’ve found that modeling your response types as unions works really well since it allows you explicitly model the errors you’re expecting. So in a createUser mutation similar to yours @jonatasbaldin you can do this:

class CreateUserFailUsernameExists(graphene.ObjectType):
	suggested_alternatives = graphene.List(graphene.String)
	error_message = graphene.String(required=True)


class CreateUserFailOther(graphene.ObjectType):
	error_message = graphene.String(required=True)


class CreateUserSuccess(graphene.ObjectType):
	user = graphene.Field(User, required=True)


class CreateUserPayload(graphene.Union):
    class Meta:
        types = (CreateUserFailUsernameExists, CreateUserFailOther, CreateUserSuccess)


class CreateUser(graphene.Mutation):
	class Arguments:
		username = graphene.String(required=True)
		password = graphene.String(required=True)
	
	Output = CreateUserPayload

	def mutate(root, info, username, password):
    	if User.objects.filter(username=username).exists():
			return CreateUserFailUsernameExists(
				error_message="Username already exists",
				suggested_alternatives=get_alternatives(username)
			)
		try:
			user = create_user(username, password)
			return CreateUserSuccess(user=user)
		except:
			return CreateUserFailOther(error_message="Something went wrong")

Then in your client your mutation query becomes:

mutation createUser($username, String!, $password: String!) {
	createUser(username: $username, password: $password) {
		__typename
		... on CreateUserFailUsernameExists {
			suggestedAlternatives
		}
		... on CreateUserFailOther {
			errorMessage
		}
		... on CreateUserSuccess {
			user {
				id
			}
		}
	}
}

Then you just need to check the __typename value to figure out if there was an error (and what kind) or if the mutation succeed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Custom Error Messages in Spring REST API - amitph
The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the...
Read more >
Custom Error Message Handling for REST API - Baeldung
Custom Error Message Handling for REST API · 1. Overview · 2. A Custom Error Message · 3. Handle Bad Request Exceptions ·...
Read more >
Get Started with Custom Error Handling in Spring Boot (Java)
First, you have to think about all the HTTP error status codes you want your application to return. Then, you have to define...
Read more >
Return custom error message in ASP.NET Core Web Api
I am writing a webapi in ASP.NET CORE 1.1 . I am trying to figure out how to return error message with not...
Read more >
Return a custom error message in SQL Server - Tech Funda
To return custom error message in case of error, we pass necessary parameter to the THROW statement. --- SELECT 'ITFunda'/0 BEGIN TRY SELECT...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found