Exception type for "invalid operations"?

Domenic Denicola domenic at domenicdenicola.com
Thu Jan 30 08:25:00 PST 2014

I'm trying to design the [whatwg/streams spec][1] in the style of ECMAScript primitives, since I find that style more precise and idiomatic, and potentially in the future streams could become a language-level feature. Basically, I want to get ahead of the situation `TextEncoder`/`TextDecoder` find themselves in, as per [recent discussions][2].

One thing I'm stuck on is what exception type to use for invalid operations. For example, trying to read from or write to a closed stream. None of the ECMAScript standard types---`EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, and `URIError`---seem to match. Do I just give up and use `TypeError`, which seems to be the catch-all in most situations?

Or would it make sense to open ourselves up beyond the existing set, and define some kind of `InvalidOperationError`? The idea being that, *if* streams were to become an ECMAScript primitive, so would `InvalidOperationError`. (*If*, not when! Please don't read too much presumptuousness into my API design predilections.)

Other languages seem to have something similar: [.NET's `InvalidOperationException`][3] and [Java's `IllegalStateException`][4] come to mind. But of course they have much deeper exception hierarchies, which I don't think we want to emulate.

[1]: https://github.com/whatwg/streams
[2]: http://esdiscuss.org/topic/need-a-champion-stringview-strawman#content-17
[3]: http://msdn.microsoft.com/en-us/library/system.invalidoperationexception%28v=vs.110%29.aspx
[4]: http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html

More information about the es-discuss mailing list