Created
May 8, 2020 09:01
-
-
Save olehcambel/70fda503bf5ff8f7012f4221fb60dcb9 to your computer and use it in GitHub Desktop.
A way to recover from panic (regexp) and return error.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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