Python graphql.format_error() Examples

The following are 8 code examples of graphql.format_error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module graphql , or try the search function .
Example #1
Source File: test_query.py    From gql with MIT License 6 votes vote down vote up
def test_parse_error(client):
    with pytest.raises(Exception) as exc_info:
        gql(
            """
            qeury
            """
        )
    error = exc_info.value
    assert isinstance(error, GraphQLError)
    formatted_error = format_error(error)
    assert formatted_error["locations"] == [{"column": 13, "line": 2}]
    assert formatted_error["message"] == "Syntax Error: Unexpected Name 'qeury'." 
Example #2
Source File: __init__.py    From graphql-server-core with MIT License 5 votes vote down vote up
def encode_execution_results(
    execution_results: List[Optional[ExecutionResult]],
    format_error: Callable[[GraphQLError], Dict] = format_error_default,
    is_batch: bool = False,
    encode: Callable[[Dict], Any] = json_encode,
) -> ServerResponse:
    """Serialize the ExecutionResults.

    This function takes the ExecutionResults that are returned by run_http_query()
    and serializes them using JSON to produce an HTTP response.
    If you set is_batch=True, then all ExecutionResults will be returned, otherwise only
    the first one will be used. You can also pass a custom function that formats the
    errors in the ExecutionResults, expecting a dictionary as result and another custom
    function that is used to serialize the output.

    Returns a ServerResponse tuple with the serialized response as the first item and
    a status code of 200 or 400 in case any result was invalid as the second item.
    """
    results = [
        format_execution_result(execution_result, format_error)
        for execution_result in execution_results
    ]
    result, status_codes = zip(*results)
    status_code = max(status_codes)

    if not is_batch:
        result = result[0]

    return ServerResponse(encode(result), status_code) 
Example #3
Source File: __init__.py    From graphql-server-core with MIT License 5 votes vote down vote up
def format_execution_result(
    execution_result: Optional[ExecutionResult],
    format_error: Optional[Callable[[GraphQLError], Dict]] = format_error_default,
) -> FormattedResult:
    """Format an execution result into a GraphQLResponse.

    This converts the given execution result into a FormattedResult that contains
    the ExecutionResult converted to a dictionary and an appropriate status code.
    """
    status_code = 200
    response: Optional[Dict[str, Any]] = None

    if execution_result:
        if execution_result.errors:
            fe = [format_error(e) for e in execution_result.errors]  # type: ignore
            response = {"errors": fe}

            if execution_result.errors and any(
                not getattr(e, "path", None) for e in execution_result.errors
            ):
                status_code = 400
            else:
                response["data"] = execution_result.data
        else:
            response = {"data": execution_result.data}

    return FormattedResult(response, status_code) 
Example #4
Source File: __init__.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __format_error(self, error):
        if isinstance(error, GraphQLError):
            return format_graphql_error(error)

        return {'message': str(error)} 
Example #5
Source File: pytest.py    From flask-unchained with MIT License 5 votes vote down vote up
def _raise_non_graphql_exceptions(error):
    if isinstance(error, graphql.GraphQLError):
        return graphql.format_error(error)

    raise error 
Example #6
Source File: pytest.py    From flask-unchained with MIT License 5 votes vote down vote up
def __init__(self, schema=None, format_error=None, **execute_options):
        super().__init__(schema or unchained.graphene_bundle.root_schema,
                         format_error=format_error or _raise_non_graphql_exceptions,
                         **execute_options) 
Example #7
Source File: base.py    From graphql-ws with MIT License 5 votes vote down vote up
def execution_result_to_dict(self, execution_result):
        result = OrderedDict()
        if execution_result.data:
            result['data'] = execution_result.data
        if execution_result.errors:
            result['errors'] = [format_error(error)
                                for error in execution_result.errors]
        return result 
Example #8
Source File: app.py    From graphql-ws with MIT License 5 votes vote down vote up
def graphql_view(request):
    payload = await request.json()
    response = await schema.execute(payload.get('query', ''), return_promise=True)
    data = {}
    if response.errors:
        data['errors'] = [format_error(e) for e in response.errors]
    if response.data:
        data['data'] = response.data
    jsondata = json.dumps(data,)
    return web.Response(text=jsondata, headers={'Content-Type': 'application/json'})