sindresorhus / serialize-error

Serialize/deserialize an error into a plain object
MIT License
538 stars 62 forks source link

Add option to decide behavior #25

Open sindresorhus opened 5 years ago

sindresorhus commented 5 years ago

You can throw anything in JS, but it's a bad practice. I'd like to have it fail rather than silently accept anything. Though, it's not a good default, so should be opt-in.

Actually, there's 3 possible behaviors:

  1. Always return an object. (wanted default)
  2. Passthrough non-object values. (current default)
  3. Throw on non-object input.

I'd like 1 to be the default behavior, for consistency, but add an option to be able to opt into 2 (which is the current behavior) or 3 (which would be the strict behavior). This should be a single option.

Another benefit of 1 is that the TypeScript types can be better. We can guarantee it's an object and we can also guarantee that the name, message, and stack properties exist.

sindresorhus commented 5 years ago

// @OsoianMarcel @samchon @semmel I could use some opinions on this.

semmel commented 5 years ago

Yes, in practice all sorts of crap is thrown. Other than non-objects, e.g. objects which contain a collection of several errors and root level name, message nor stack.

My expectation from serialize-error would be that it produces something "serializable" from my input. If that is possible it should not fail. Thus I don't like option 3.

Another benefit of 1 is that ... we can also guarantee that the name, message, and stack properties exist.

Yes, but the values of name and stack would not be very useful, would they?

I can imagine some mapping from non-object primitives to .message simply like serializableError.message = String(nonObject) That would work for non-objects like Strings (non-empty), Numbers, Symbols, Dates ...

But what would the message property be for {foo: "bar", doc: window.document}?

sindresorhus commented 5 years ago

Yes, but the values of name and stack would not be very useful, would they?

They would be useful in the sense that they would indicate that an invalid error was passed.

But what would the message property be for {foo: "bar", doc: window.document}?

It would use util.inspect, same as: https://github.com/sindresorhus/serialize-error/blob/480ed369823b089ac8c75092d59c1d1f7390350e/index.js#L76

semmel commented 5 years ago

Requiring the Node.js built-in util package for util.inspect means that serialize-error no longer works in a browser?

Otherwise I would be polite to add a build step to generate some distribution files for the browser using a util shim?

jcald1 commented 4 years ago

@semmel , you can install util in package.json for the browser.