Skip to content

Instantly share code, notes, and snippets.

@olehcambel
Created May 8, 2020 09:01
Show Gist options
  • Save olehcambel/70fda503bf5ff8f7012f4221fb60dcb9 to your computer and use it in GitHub Desktop.
Save olehcambel/70fda503bf5ff8f7012f4221fb60dcb9 to your computer and use it in GitHub Desktop.
A way to recover from panic (regexp) and return error.
// Error is the type of a parse error; it satisfies the error interface.
type Error string
func (e Error) Error() string {
return string(e)
}
// error is a method of *Regexp that reports parsing errors by
// panicking with an Error.
func (regexp *Regexp) error(err string) {
panic(Error(err))
}
// Compile returns a parsed representation of the regular expression.
func Compile(str string) (regexp *Regexp, err error) {
regexp = new(Regexp)
// doParse will panic if there is a parse error.
defer func() {
if e := recover(); e != nil {
regexp = nil // Clear return value.
err = e.(Error) // Will re-panic if not a parse error.
}
}()
return regexp.doParse(str), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment