Add a formatError function that tries harder to display useful error information

Fixes #1124.