lestrrat-go / libxml2

Interface to libxml2, with DOM interface
MIT License
230 stars 55 forks source link

Error details leaking #106

Closed whitlockjc closed 2 months ago

whitlockjc commented 2 months ago

Whenever I try to compile or use an invalid XPath, while an error is returned as expected, two things happen that shouldn't be:

  1. The error is missing the inner context
  2. The inner context is written to stdout/stderr (not sure which) without any control

Here is the important part of my code:

    doc, err := libxml2.Parse(docBytes)
    if err != nil {
        return err
    }

    expr, err := xpath.NewExpression(xPath)
    if err != nil {
        return err // Never contains the reason for the compilation failure
    }
    defer expr.Free()

    root, err := doc.DocumentElement()
    if err != nil {
        return err
    }

    ctx, err := xpath.NewContext(root)
    if err != nil {
        return err
    }

    res, err := ctx.FindExpr(expr)
    if err != nil {
        return err
    }
    defer res.Free()

    nodes := res.NodeIter()

    for nodes.Next() {
        node := nodes.Node()

        fmt.Printf("%s:\n%s\n", xml.XPathFromNode(node), xml.NodeToString(node))
    }

    return nil

The returned error will always/only contain failed to compile expression: xpath compilation failed but the inner error details are not available no matter how much I unwrap. Also, the inner error details always end up being written to stdout/stderr. Here is example output of my cobra CLI app that uses the code above:

myapp command -x '$.character' /tmp/library.xml
XPath error : Expected $ for variable reference
$.character
 ^
Error: failed to compile expression: xpath compilation failed
Usage:
  referee resolve [flags] DOCUMENT_PATH

Flags:
  -x, --xpath string           The XPath to resolve
  -h, --help                   help for resolve

failed to compile expression: xpath compilation failed

As you can see, the error my app returns does not contain the XPath error details and it is printed before my app prints anything related to the command returning an error. If I printed out the error returned by xpath.NewExpression, it literally only contains failed to compile expression: xpath compilation failed while XPath error: Expected $ for variable reference ... is printed to stdout/stderr but not available by the provided error, nor is there any control on whether the detailed cause is printed at all.

go version go version go1.23-20240626-RC01

github-actions[bot] commented 2 months ago

This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] commented 2 months ago

This issue was closed because it has been stalled for 7 days with no activity. This does not mean your issue is rejected, but rather it is done to hide it from the view of the maintains for the time being. Feel free to reopen if you have new comments