1

Existing Magento GraphQLExceptions return 200-th http code.

What would be a correct way to throw 401 for example? Or at least show custom status code in response.

1 Answer 1

2

There is no way to do so without modifying (create a plugin, observer or overwrite) the basic Magento controller responsible for GraphQL.

You can check how it is realised in Magnento in the vendor/magento/module-graph-ql/Controller/GraphQl.php in method dispatch:

/**
 * Handle GraphQL request
 *
 * @param RequestInterface $request
 * @return ResponseInterface
 * @since 100.3.0
 */
public function dispatch(RequestInterface $request): ResponseInterface
{
    $this->areaList->getArea(Area::AREA_GRAPHQL)->load(Area::PART_TRANSLATE);

    $statusCode = 200;
    $jsonResult = $this->jsonFactory->create();
    $data = $this->getDataFromRequest($request);
    $result = [];

    $schema = null;
    try {
        /** @var Http $request */
        $this->requestProcessor->validateRequest($request);

        $query = $data['query'] ?? '';
        $variables = $data['variables'] ?? null;

        // We must extract queried field names to avoid instantiation of unnecessary fields in webonyx schema
        // Temporal coupling is required for performance optimization
        $this->queryFields->setQuery($query, $variables);
        $schema = $this->schemaGenerator->generate();

        $result = $this->queryProcessor->process(
            $schema,
            $query,
            $this->contextFactory->create(),
            $data['variables'] ?? []
        );
    } catch (\Exception $error) {
        $result['errors'] = isset($result['errors']) ? $result['errors'] : [];
        $result['errors'][] = $this->graphQlError->create($error);
        $statusCode = ExceptionFormatter::HTTP_GRAPH_QL_SCHEMA_ERROR_STATUS;
    }

    $jsonResult->setHttpResponseCode($statusCode);
    $jsonResult->setData($result);
    $jsonResult->renderResult($this->httpResponse);

    // log information about the query, unless it is an introspection query
    if (strpos($data['query'], 'IntrospectionQuery') === false) {
        $queryInformation = $this->logDataHelper->getLogData($request, $data, $schema, $this->httpResponse);
        $this->loggerPool->execute($queryInformation);
    }

    return $this->httpResponse;
}

For your purpose you can create a plugin for this method and correct a status code in response. Also you can update the body in the response object in such a plugin.

By default there is two status codes available: 200 (regular) and 500 (any uncaught exception).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.