130 points · by fagnerbrack · 2y ago · 171 comments
Now, to be fair, having a public constructor for URL with just a string as the argument, with the parsing semantics is arguably an anti-pattern, and a static factory function would serve much better indeed. A proper public URL constructor should instead take (scheme, authority, path, query, fragment) tuple and validate its constituents. The private URL constructor could be the one without validation, and that's what parse() and the public constructor would call internally.
A very similar thing, the Result type in Rust, does pretty well. (Much like Maybe / Either do in Haskell.)
However, when high profile people criticise it, they criticise it because, for example, interfaces work terribly with checked exceptions. There are problems with collections for example. Like when filesystem backs a list, then that list cannot throw IOException. This is why there is RuntimeIOException now.
I think the backlash against them was way too hard to the point that basically no other mainstream language dared trying them out, even though exceptions in general are - in my slightly subjective opinion - the best form of error handling, paired with some static guarantees sounds like an optimum. They do the correct thing by default (auto-unwrap in the happy case, auto-bubble up with a stacktrace in the unhappy one), and let’s one control their handling on as wide or narrow scope as required (try blocks). Nonetheless, I think that they are to be used for exceptional situations, like network interrupts, OS errors, etc. Expected error conditions, like parsing a number failing is best encoded as a sum type, analogously to an Either/Result type.
Newer research languages with effect types might resurface this “lost” idea, I’m definitely looking forward to them.
And you know, I think I can safely bet $5 the way TFA came to be was something like this: the author wrote a code that used URL() with no error recovery-path whatsoever, ran it, and it blew up on that line. The author then rolled its eyes, wrote an (admittedly) ugly try-catch around, and went to write the article complaining about exception.
Now, I can bet another $5 that if URL() returned null what would happen instead would be that the author would write a code that used URL() with no error recovery-path whatsoever, would run it, and it would blow up somewhere down the line, on call to fetch() or something. The author would then ponder the code for several minutes, trying to figure out what exactly fetch() didn't like about the URL it was provided with, find that null came from the call to URL() and add the error recovery there. Crucially, they later would not go and write a article complaining about null returns because they regard it as a completely normal and acceptable behaviour.
`let fooOrNil = try? Foo("blah")`
Edit: Updated URL to Foo, since Swift happens to use optional return for its own 'URL' type, as pointed out.
I find monadic error handling (`Result<T, E>` and `Option<T>`, or `Either<T, U>` and `Maybe<T>` if you prefer Haskell) to be much better at keeping error handling logic local to where errors originate, and making it explicit which operations are fallible and what errors they produce. Exceptions tend to be nonlocal and difficult to determine what exceptions can occur from where.
That sugar for getting an optional/nullable value with `try?` definitely looks nice, I wish Python had something like that, but it seems to me that the reason it works better is that it's closer to monadic error handling (you get an `Option<T>`).
Has your experience been different?
func someThrowingFunc() throws -> T
let someResult = Result(catching: { try someThrowingFunc() }) // someResult: Result<T, any Error>
Or the other way: let someResultFunc() -> Result<T, any Error>
let t = try someResultFunc().get() // t: T
The reason I say they’re not “real” exceptions is that it compiles down to a branch that checks if a particular error return register is non-nil, same as you would with a result type. (As opposed to “real” exceptions like in C++ where execution is forcefully interrupted by an expensive exception handler.)I started out in swift treating it like rust and using Result everywhere, and manually chaining results back up when I didn’t want to handle them, but after a while I realized that the `throws` and `try` statements were just way more readable syntax to accomplish the same thing I was already doing:
Want to “not care” about the thrown error? Use `try?`. Want to propagate it up? Use `try` and just mark your function as throws rather than explicitly returning a Result. Want to crash on an error? Use `try!`. Want to explicitly deal with the error? Use `catch`, or if you don’t like that syntax and you’d prefer matching on a success/error enum you can just convert it to a Result as I outlined above.
This is true statically (mitigated by checked exceptions in Java, but that's a whole can of worms on its own), but the opposite is true when you actually have an error at runtime—exceptions come bundled with stack traces which make it very easy to see the stack of function calls that get us into the failure state, where with result types you at best have a (hopefully descriptive) error message and that's it.
If the code has already been well polished then that error message is probably enough, but if you're still ironing out rough edges the error message itself may be in error and the actual problem may be somewhere else entirely. With a stack trace you can easily see the function calls that got into that unexpected state, but without them you're on your own and have to try to recreate the error while stepping through in the debugger.
(My perspective is Rust centric, and if you eg unwrap an error because you mistakenly thought it shouldn't be reachable, you end up with a panic which is just an exception.)
I should specify that throwability needs to be part of the function signature to be useful in the language. As for what types of errors: At minimum they should provide something you can show a user, maybe after adding context, and the machine-readable codes should be documented, both of which are points of failure, but the ability is there.
Interestingly, Swift is getting typed exceptions, which seems too good to be true. I'm not sure how it works when passing exceptions up the call chain.
As for Optional/Maybe, as I replied to a sibling, that's not really comparable. It's not for error-handling because it doesn't provide an error. It's useful for when something might not exist, but not so much for when some input is invalid, etc, since it's more verbose to explicitly fork on null and return early.
As for Result<T,E>, it has a subset of the same problems: Can't pass it up without writing a fork/switch unless it's just a wrapper function that returns Result<T,E>. And it makes things less composable or require extra forks when something is expecting T. But, like Optional, it definitely has uses: Like if you're using a callback system for an async function, where throwing is impossible.
You can think of `Optional<T>` as being `Result<T, null>` - it's a fallible operation where there is either one obvious way it can fail or where we don't care to distinguish between them. If you look a key up in a map, that's a fallible operation, but there's only one way for it to fail - the key wasn't present in the dictionary. It's definitely error handling.
`Result` really comes into it's own when combined with pattern matching (`switch` with destructuring and exhaustiveness, so compilation will fail if you've neglected to handle a certain error case (!!!)). Rust adds syntactic sugar and other features that make this very ergonomic. Eg, there's a `?` operator that will return early if there is an error, and traits (interfaces) that make it seamless to convert one error into another, add error messages, etc.
> it makes things less composable
Not so! They're very composable, eg:
let x = my_fallible_operation().map(|v| do_something_on_success(v)).or(other_fallible_operation_to_compose_with())
If `my_fallible_operation()` success, `x` will be `Ok(do_something_on_success(v))`; otherwise, it will be the return value of `other_fallible_operation_to_compose_with()` (itself a result).Are you saying that Result<T, E1> doesn't convert to Result<T, E2> automatically? Cause I've had great success implementing `From<E1> for E2` and forwarding the error via `?`. There's also map and unwrap helpers to convert. If you're saying that Result<T, E> is incompatible with a return type of T, that's often seen as a benefit because they are incompatible and you have to choose how to bridge that gap by for example unwrapping because you don't expect an error (equivalent to not specifying a catch and letting the thread terminate) or somehow else doing something with that error (specifying a catch handler). What it doesn't let you do is ignore the failure case silently and implicitly.
As for sum types, it is definitely not good practice, but I would say that if you fail to handle an error condition close to its source, and it managed to get to some “global” scope, determining where it originates is very hard. Similar to that illegal database row that somehow managed to get entered, resulting in a difficult investigation.
I think it's fundamentally less local to do a conditional jump elsewhere in the code (even if doesn't cross into a different frame) than to return a value and step to the next line, rain or shine. I don't disagree that there's an isomorphism between the approaches (since they're both addressing the same need, surely there should be), but exceptions introduce a new set of rules whereas monadic error handling repurposes the familiar semantics of function calls.
But you're not the first person to mention your second point, so I totally concede that, regardless of whether it is "bad practice," empirically it's a weakness of the approach.
What are the reasons you think it's better than Either and map, especially for expected control flow that doesn't signify programmer error and just responds to bad input data? I can't see any upsides. The function doesn't force the caller to handle the error, and the error isn't type checked: if the function stops throwing one type of exception or starts throwing another, type system won't force outdated call sites to be fixed.
Regardless: Why would it be a bad use of exceptions? It reduces the API size and unifies flows, and gives me the option of seeing the specific error. It simply happens to be that in practice I've never needed to know the specific error in this case.
You grew up with "errno only", so that's your frame of reference. You've seen exceptions and don't want to go back to errno. Do you "fear" errno? Is errno the "boogey man"?
I've seen monadic error handling and I don't want to go back to exceptions.
Many languages make it idiomatic for functions to return a value or error (Rust, Go, modern C++) so that you can access a human-friendly error on failure.
https://doc.rust-lang.org/std/result/
https://go.dev/doc/tutorial/handle-errors
https://en.cppreference.com/w/cpp/utility/expected (there's also std::variant and std::optional that can get you there since C++17)
I have been referring to try/catch error-handling, but have used the word "exception" as a synonym a couple times, and I think a couple other people have made the same assumption of synonymity in their replies.
Really, "exception" should be reserved to refer to things that "shouldn't happen", that we don't want to waste resources recovering from. In most languages, try/catch is exclusively for exceptions, and they are sometimes/always unchecked, but in Swift, try/catch is for plain errors, and the compiler forces you to handle them. This is a huge caveat, and a mistake on my part, that makes 50% of the conversation moot. I am only lauding try/catch error-handling, and checked i.e. enforced try/catch at that, but not exceptions.
Saying "I prefer Maybe to try/catch" is too broad - it's almost like saying you prefer not to handle errors.
If you were forced to handle exceptions at every call site I might find myself able to agree, but then you have something functionally equivalent to options. I'd much rather just start with that approach.
If you write library code, fail polymorphically, then the client can choose whether they want to call it as Maybe/Either/Exception and we can stop these never-ending arguments.
Maybe/Either/Result is a way to represent partial computations at runtime.
try/catch is a syntax to detect partial computations and to do something conditionally if one occurs.
You could have a language that used try/catch syntax to catch Result types, indeed Rust does something like this with the try operator although it’s only try/catch if you squint very hard.
The best error handling pattern for scripts we've figured out so far, but at the same time the worst error handling pattern for systems known to man.
But it not fun when writing systems. That is why we have different tools for different jobs.
However, it is the `try...catch` pattern that messes up with the `const`, not the URL constructor. It is very annoying every time when I have to wrap an existing block with a try...catch, and inevitably lose the const-ness to some variables, unless I wrap everything again into a function and `return` in the try block if things go normally.
https://github.com/nzakas/proposal-write-once-const?tab=read...
const result = (() => {
try {
return new URL(someString)
} catch {
return null
}
})()
It's not pretty though, and I think the do expressions proposal would rid my codebases of this pattern: https://github.com/tc39/proposal-do-expressionsAs far as other error return patterns existing in "the spec" - there are multiple specs referred to here (ECMA vs DOM) & also multiple eras; there seems to be consensus that some past patterns on error return weren't great decisions & some well considered consensus to move to more broadly accepted known patterns (like try/catch).
e.g. for your Date example, that's a really old API that ECMA are working on replacing with Temporal (which throws)
So this is a no-brainer.
if (typeof URL.parse != 'function') {URL.parse = function (_s){let _ret; try { _ret = new URL(_s)} catch {}; return _ret} } ;
const tryNew = (f, ...a) => {
try {
return new f(...a);
} catch(x) {
return undefined;
}
};
const myUrl = tryNew(URL, 'http://example.com/');I don't get why JS devs like to whinge about the smallest things. And we get stuff like leftPad because of huge aversion to writing utility functions.
Does every dev need to write the same line now? Or should your one-liner be a library?
The basics that everybody needs, should be standardized in the standard library.
Yes.
> Or should your one-liner be a library?
Definitely not.
Particularly if I can write the one-liner faster than it takes one to search, check, include and install the library.
On the other hand, you don't want to be Java, where List.Last took until Java 21 to get implemented. It's not hard to make a wrapper function, but it's really annoying to clutter your code with helper functions where the native API should help you.
In this specific instance, I agree with the new spec: most constructors for native Javascript types don't throw, so neither should the URL constructor. However, the try/catch isn't exactly the problem some people seem to think it is. It's a minor annoyance that apparently annoyed at least three browser teams enough to come up with a new API. In other circumstances, I hope the API spec won't be extended as easily.
Can you explain how helpers create exploits? Are there any examples?
It's easier to secure a JIT with 100 methods than it is to secure a JIT with a thousand.
I understand people might not like exceptions, but special-casing certain calls like just makes the language harder to use.
For example, on google.com, you can find:
<img class="lnXdpd" alt="Google" height="92" src="/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
But open the console and run this, and it will throw:
let x = new URL("/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
You're supposed to address this by adding the base URL on the end, but then correctly obtaining that can be brittle. If you're browsing a folder, the whole document.location is the baseURL, but if you are browsing a file (ie ends in .php or .html) it isn't. If you're taking user URLs, your browser's URL bar will add https:// automatically so people don't think about it, but they'll leave it out of an absolute URL and now you need to detect and add it if needed.
> If you're browsing a folder, the whole document.location is the baseURL, but if you are browsing a file (ie ends in .php or .html) it isn't
I’m not sure I understand what you’re saying here. The second argument in the URL constructor works as a “relative to” argument. If your URL starts with / it doesn’t matter if there’s a file or not, it’ll start from the domain root.
www.example.com + /images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com/static/ + /images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com/static/index.html + /images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com + images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com/static/ + images/foo.jpg -> www.example.com/static/images/foo.jpg
www.example.com/static/index.html + images/foo.jpg -> www.example.com/static/index.htmlimages/foo.jpg (naive and wrong)
-> www.example.com/static/images/foo.jpg (extra work)
They were referring to the difference between the 5th and 6th (probably didn't notice it was an absolute path), you're referring to the first 3 together vs the others. www.example.com/static/index.html + ./images/foo.jpgI think you just misunderstand what a URL is.
The bigger point is yeah, type T isn't a parser for type U.
I guess unfortunately, I'm not sure if there is a URI-ref parser in JS that I know of … but does one ever want to do that, without first normalizing it over a base URI?
Isn't that what document.baseURI is for? At least that's my understanding:
new URL("/whatever", document.baseURI)
For instance, an empty mailto: will reliably launch an email client, even if no address is specified. I think it's the second most used protocol in web links, after HTTP(S).
If you want to to URL parsing by brute forcing URL constructors, you probably don't want application URLs in the first place. You should probably start with https:// and http://, or make use of the weird double slash HTTP introduced into the URL by matching on :// instead.
If you want to get real anal about it the API should probably called URI instead of URL. The latter should describe where to access the resource, not just how to identify it, and to truly be able to do that you must also know something about the scheme.
At the very least you must know whether the scheme imposes further restrictions on the individual parts of the URI, otherwise you can only determine whether it's a valid URI but not truly say whether it's a valid URL.
In practice no one really cares much about the distinction between identifiers and locators, and arguably it was a mistake to try and make that distinction in the spec. But it is in there after all and I find it a bit ironic that the authors of the JS spec chose to ignore it. There's probably good reason for it, but still.
Ps. I'm real fun at parties!
However, I check back in from time to time and was recently confused as to whether or not the community has moved onto effect-ts as it seems effect consumed the fp project?
Do you have any context on that?
Mostly responding so people with better context don't wait on me.
Practically, though, I like it because JavaScript’s error handling sucks. I generally avoid using try/catch as a first class member of my software.
But the semantics around try/catch are the main issue here and basically everywhere in JS. Error catching in JS is absolutely abysmal. Some examples:
- nested try catch
- not annotating that a function throws an error (or even being able to annotate in TS that it does)
- async code throwing an error in a callback is uncatchable. E.G. file reader onread throwing an error.
- not being able to narrow a catch to a specific error type.
Compare
let url = Url.parse(str)?;
To let url; // invalid state
try {
url = new Url(str)
} catch (e) {
return ...
}> You could have a language that uses "?" as sugar for the more wordy try-catch-return code that you've written here.
I do! (it's ">>=" though, not "?").
> These examples aren't really showing the semantic difference between errors as values and thrown errors, which is the implicit propagation across multiple code locations.
Well here's where we can start to go in circles. I like errors as values, and I dislike Checked Exceptions. But I've seen others argue that Result and Checked Exceptions are completely equivalent. Different people have different ideas about what the semantics are.
In many cases that's enough to handle an error. It's still not a great comparison, since implicitly letting the exception propagate is the closest correspondence in a language that uses exceptions for expected errors.
It’s not really implicit though, is it? You’re explicitly asking the language to unwrap the result or propagate the error up out of the function. And the function return value explicitly encodes this, unlike exceptions which can happen anywhere for any reason at any time.
Now, arguably the original API wasn’t the best, but this is really not the way to design an API. There should preferably only be one way to do things and consistency with the rest of the library should be kept. Finally, don’t forget about browser compatibility.
As many others already argued, the root cause can be solved with just a sprinkle of syntax sugar to aid with try/catch.
Yes, but you don't have the overhead of constructing URL first. The new URL.canParse method from the article covers this.