Spring Boot GraphQL Exception Handling

Error handling is one of the important parts of programming language. Spring Boot GraphQL provides an ErrorClassification interface that classifies errors into multiple parts.

  • BAD_REQUEST
  • UNAUTHORIZED
  • FORBIDDEN
  • NOT_FOUND
  • INTERNAL_ERROR

The exception that doesn't fall in the below category will automatically consider an Internal Error with a generic message

GraphQL supports custom error handlers by extending an abstract class DataFetcherExceptionResolverAdapter.

package org.wesome.graphql.config;

import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import graphql.schema.DataFetchingEnvironment;
import jakarta.security.auth.message.AuthException;
import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;

@Component
class CustomErrorMessageExceptionResolver extends DataFetcherExceptionResolverAdapter {
    @Override
    protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
        GraphQLError error = GraphqlErrorBuilder.newError(env)
                .errorType(ErrorType.INTERNAL_ERROR)
                .message("There are some internal error")
                .build();
        if (ex instanceof IllegalArgumentException) {
            error = GraphqlErrorBuilder.newError(env)
                    .errorType(ErrorType.BAD_REQUEST)
                    .message("There are some bad request")
                    .build();
        }
        if (ex instanceof IllegalAccessException) {
            error = GraphqlErrorBuilder.newError(env)
                    .errorType(ErrorType.FORBIDDEN)
                    .message("you are forbidden")
                    .build();
        }
        if (ex instanceof FileNotFoundException) {
            error = GraphqlErrorBuilder.newError(env)
                    .errorType(ErrorType.NOT_FOUND)
                    .message("The resource you are looking for is not found")
                    .build();
        }
        if (ex instanceof AuthException) {
            error = GraphqlErrorBuilder.newError(env)
                    .errorType(ErrorType.UNAUTHORIZED)
                    .message("You are unauthorized")
                    .build();

        }
        return error;
    }
}
package org.wesome.graphql.controllers;

import com.sun.jdi.InternalException;
import jakarta.security.auth.message.AuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
import org.wesome.graphql.entity.Apple; 

import java.io.FileNotFoundException;

@Controller
public class AppleGraphQLController { 

    @QueryMapping("InternalError")
    Apple internalError() {
        throw new InternalException("Internal Error occurred");
    }

    @QueryMapping("badRequest")
    Apple badRequest() {
        throw new IllegalArgumentException("badRequest received");
    }

    @QueryMapping("forbidden")
    Apple forbidden() throws IllegalAccessException {
        throw new IllegalAccessException("illegal access to the resource");
    }

    @QueryMapping("notFound")
    Apple notFound() throws FileNotFoundException {
        throw new FileNotFoundException("resource not found");
    }

    @QueryMapping("unauthorized")
    Apple unauthorized() throws AuthException {
        throw new AuthException("unauthorized access");
    }
}
package org.wesome.graphql.entity;

public record Apple(int appleId, String appleName, String appleTaste, String now) {
}
package org.wesome.graphql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GraphqlProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(GraphqlProjectApplication.class, args);
    }
}

\src\main\resources\graphql\schema.graphqls

# Apple Object
type Apple{
    # primary key of apple
    appleId:ID!
    # apple Name
    appleName:String
    # apple AppleTaste
    appleTaste:String
    # current time
    now : String
}
# Apple Query
type Query{
    #    Error message resolver for InternalError
    internalError:Apple
    #    Error message resolver for IllegalArgumentException
    badRequest:Apple
    #    Error message resolver for IllegalAccessException
    forbidden:Apple
    #    Error message resolver for FileNotFoundException
    notFound:Apple
    #    Error message resolver for IllegalAccessException
    unauthorized:Apple
}

\src\main\resources\application.properties

spring.graphql.graphiql.enabled=true

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.5</version>
        <relativePath/>
    </parent>
    <groupId>org.wesome</groupId>
    <artifactId>spring-boot-graphql</artifactId>
    <version>0.0.1-snapshot</version>
    <name>spring boot graphql</name>
    <description>implementing graphql in spring boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.graphql</groupId>
            <artifactId>spring-graphql-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

GraphiQL

GraphQL provides an inbuild UserInterface GraphiQL, which can be accessed via http://localhost:8080/graphiql or access GraphQL via Postmanin the query section add the below query

InternalError

query InternalError{
    internalError {
        appleId
        appleName
        appleTaste
        now
    }
}

BadRequest

query BadRequest{
    badRequest{
        appleId
        appleName
        appleTaste
        now
    }
}

Forbidden

query Forbidden{
    forbidden{
        appleId
        appleName
        appleTaste
        now
    }
}

NotFound

query NotFound{
    notFound{
        appleId
        appleName
        appleTaste
        now
    }
}

Unauthorized

query Unauthorized {
    unauthorized{
        appleId
        appleName
        appleTaste
        now
    }
}

follow us on