Closed 5idu closed 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.
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
}
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!