graphql-python / graphql-server

This is the core package for using GraphQL in a custom server easily
MIT License
120 stars 72 forks source link

Stack traces in graphql errors #80

Open EmrysMyrddin opened 3 years ago

EmrysMyrddin commented 3 years ago

Hi,

It would be great for development purpose to include exception stack traces to graphql errors returned by graphql-server.flask when it catches an exception during the execution of a request.

For security reasons, I think it shouldn't be enabled by default, but at least offer the option to do it, since for now, it's just not possible to do.

The only way I found to debut an error is to place a break point in graphql-server.flask.GraphQLView.dispatch_request method in the excpect handler... which is not very convenient.

If you are open to the idea, I can make a PR to poc around this feature.

guillaumep commented 2 years ago

Found a way to obtain stack traces and to log them server-side.

Define a middleware function like this:

import logging

def exception_logging_middleware(next, root, info, **args):
    try:
        return_value = next(root, info, **args)
    except Exception as e:
        logging.exception(e)
        raise
    return return_value

And provide it to the middleware parameter when using GraphQLView.as_view:

from graphql_server.flask import GraphQLView

def publicapi_view():
    return GraphQLView.as_view(
        "publicapi",
        # public_schema is an instance of graphene.Schema
        schema=public_schema.graphql_schema,
        middleware=[exception_logging_middleware],
    )

# app here is the Flask app
app.add_url_rule("/publicapi", view_func=publicapi_view(), methods=["POST"])

Tested with the following versions:

flask==2.0.2
graphene==3.0
graphql-core==3.1.7
graphql-server==3.0.0b4