dop251 / goja_nodejs

Nodejs compatibility library for Goja
MIT License
329 stars 78 forks source link

How can i get details error message when a package is not found? #72

Closed 5idu closed 6 months ago

5idu commented 6 months ago

question background

when i run the script below, i got a error message: GoError: Invalid module at github.com/dop251/goja_nodejs/require.(*RequireModule).require-fm (native) but i want detailed error information, such as which package does not exist. thanks!

const xx = require('xx')
const notfound = require('notfound package')
console.log(notfound)
dop251 commented 6 months ago

You can't get it from the error itself, because it's a value, not type, but you can get the location from the stacktrace, which will point to the line of code that contains the require. If you are doing something like dynamic require, you can write a wrapper function.

5idu commented 6 months ago

maybe someone can use it in the future!

func formatGojaErr(script string, err error) error {
    ex, ok := err.(*goja.Exception)
    if ok {
        if strings.Contains(ex.String(), "Invalid module") {
            stackframes := strings.Split(ex.String(), "\n")
            if len(stackframes) > 2 {
                lines := strings.Split(stackframes[2], ":")
                if len(lines) > 2 {
                    line, err := strconv.Atoi(lines[1])
                    if err == nil {
                        errLine := strings.Split(script, "\r\n")[line-1]
                        if strings.Contains(errLine, "require") {
                            re := regexp.MustCompile(`['"]([^'"]+)['"]`)
                            match := re.FindStringSubmatch(errLine)
                            if len(match) > 0 {
                                return errors.New("Invalid module: " + match[1])
                            }
                        }
                    }
                }

            }
        }
    }

    return err
}