Skip to content

ParseResponseXML: give parse failures a richer exception message #37

Description

@jwadhams

ParseResponseXML::parseResponseString() is currently:

public function parseResponseString(string $responseString): SimpleXMLElement
{
    return new SimpleXMLElement($responseString);
}

On malformed XML, this throws a bare \Exception with the message "String could not be parsed as XML" — no detail about what was wrong with the
document, and no reference to the response body that failed to parse. That's
a meaningfully worse error than what ParseResponseJSONSchemaOrThrow gives
you on a bad JSON response (a typed UpstreamException/JsonSchemaValidationException
with the actual validation failures attached).

One of our consumers (App\Requests\UrbanScience\UrbanScienceLeadRequest,
which doesn't use this trait and instead hand-rolls its own
parseResponseString()) does noticeably better:

// Parse the response as XML or throw an exception
public function parseResponseString(string $responseBody): mixed
{
    try {
        libxml_use_internal_errors(true);
        $parsedXml = new SimpleXMLElement($responseBody);
    } catch (Exception $e) {
        $errors = [];
        foreach (libxml_get_errors() as $error) {
            $errors[] = $error->message;
        }
        libxml_clear_errors();

        throw new BadResponseException(
            502,
            $e->getMessage() . ' [ ' . implode(', ', $errors) . '] in ' . $responseBody,
        );
    }

    return $parsedXml;
}

This collects the actual libxml errors, wraps the failure in a real
"upstream sent us garbage" exception type, and includes the response body
for debugging.

I'm deliberately not asking for this exact code to be copied in — it works,
but there may well be a cleaner way to get the same result in modern PHP
(e.g. something built on simplexml_load_string() + LIBXML_NOERROR +
inspecting libxml_get_errors(), or restructuring so the caller doesn't
need libxml_use_internal_errors() global state at all). The goal is just:
a better exception message with more information about the specific
parse problem
, in the spirit of what ParseResponseJSONSchemaOrThrow
already does for JSON, and that works well all the way into the log file in v2.x code.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions