Return errors rather than doing panics.

This makes it simpler to handle errors in code importing this package.