Added toJSON function to error object

Closes #276

Because we attach error directly, which can't be stringified, add a custom `toJSON` method to step around the problem.