Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
5idu opened this issue Feb 27, 2024 · 2 comments
Closed

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

5idu opened this issue Feb 27, 2024 · 2 comments

Comments

@5idu
Copy link

5idu commented Feb 27, 2024

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
Copy link
Owner

dop251 commented Feb 28, 2024

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
Copy link
Author

5idu commented Mar 1, 2024

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
}

@5idu 5idu closed this as completed Mar 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants