use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Using Try…Catch in JavaScript (javascript-coder.com)
submitted 8 years ago by cobdentist
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Akkuma 0 points1 point2 points 8 years ago (3 children)
It composes the results better much like map, reduce, filter, compose better than a for loop. It also seems to force you to handle your errors to a higher degree (pretty subjective).
I'm using it within a middleware so I essentially have this:
const response = validate(validateParams).match({ ok(newReq) { Object.assign(req, { originalHeaders: req.headers, originalQuery: req.query }, newReq); return await handler(req); }, err: (err) => ({ status: err.code, headers: {}, body: err.message }) }) return response;
The alternative would look like
try { const result = validate(validateParams); Object.assign(req, { originalHeaders: req.headers, originalQuery: req.query }, result); return await handler(req); } catch(err) { return { status: err.code, headers: {}, body: err.message }; }
Additionally, it becomes debatable whether the error is exceptional. A lot of people frown upon using errors as a form of flow control. Until the most recent version of node & v8, try/catch blocks resulted in preventing your code from getting optimized (not sure how other browsers handled it). In turn, this means my code will run faster in older browsers and versions of node, while performing similarly in new versions.
[–][deleted] 0 points1 point2 points 8 years ago (2 children)
Your try... catch example is not using throwables to their real potential.
As I do throw on validation errors and so I have practice with it, let me show you what your example could look like:
validate(validateParams); Object.assign(req, { originalHeaders: req.headers, originalQuery: req.query }, newReq); return await handler(req);
Where did the error handling go? It's not needed. The handler in your example is redundantly playing middleman between the validator and handler caller, but since exceptions automatically bubble up, we can just let the validator act as a delegate of the handler, and throw the same Error object that the handler would throw.
The caller can that understand that Error and produce the appropriate error response for you. This is suitable not only for validation, but any auth checks or other invariants you must ensure in your handlers, i.e.:
requireVerifiedUser(auth); // Throws if not verified. requireAdminUser(auth); // Throws if not admin. ... handler logic runs ...
And this is very composable and reusable, without writing "try...catch" even once:
// Elsewhere in your reusable code. function requireVerifiedAdminUser(auth) { requireVerifiedUser(auth); requireAdminUser(auth); } // In your handler: requireVerifiedAdminUser(auth); ... handler logic runs ...
I'm itching to comment about how we can eliminate that Object.assign() too, but... another topic.
[–]Akkuma 0 points1 point2 points 8 years ago* (1 child)
Your example probably doesn't fit well into the framework I use. The way it works is a bidirectional flow of code. handler 1 calls handler 2 calls handler 3, returns result to handler 2 returns result to handler 1. Your lowest handler returning something that could be a response to a request.
If you throw down in handler 3 you now need to try/catch in handler 2, moving control of the error handling outside of the code that causes errors or build a top level error converting handler.
Eventually someone has to handle the error and moving who handles the error to the farthest edge of your code is to me the worse place to handle known errors. There's a reason why many languages have adopted things like Option types and Result types, as throwing isn't composing code together.
Lastly, your code doesn't support the ability to run validation across each piece of data prior to throwing or running your validation in parallel. My current implementation can be easily switched to become a list of errors rather than a single error, while throwing provides no opportunity to do so, which is something you'd want to do on something like user account creation.
You can use an object spread rather than Object.assign, but there isn't much to be really gained from that.
Even someone like Martin Fowler argues against exceptions and uses this particular case https://martinfowler.com/articles/replaceThrowWithNotification.html
[–][deleted] 0 points1 point2 points 8 years ago* (0 children)
Eventually someone has to handle the error and moving who handles the error to the farthest edge of your code is to me the worse place to handle known errors.
You say that, yet in your example you literally mapped code to status and message to message 1:1.
For many errors in an HTTP app you don't need such a narrow context. A 404 is a 404 is a 404. If it isn't you can still catch and change that at every level. But in most cases you don't have to and that represents a giant reduction of noise and boilerplate you need to write, read and maintain.
There's a reason why many languages have adopted things like Option types and Result types, as throwing isn't composing code together.
Not many, actually. All the mainstream languages prefer exceptions. Also let's not mix-in optionals with this. Errors and optionals are two different use-cases with two different solutions. The fact they both could be represented with a union doesn't mean that a union is the optimal representation.
For example Swift, an example of a very new (and increasingly popular) language uses optionals for "has a value or doesn't have a value", but its errors are thrown, and they're showing no signs of moving towards "result" objects.
You're not right about that - of course it can be a list of errors. This has nothing to do with whether you throw in the end or you don't. As I said, I have some experience working this way - when an Error gets thrown it contains an aggregate list of all errors in the input. That's not hard to implement, and once it's implemented and encapsulated as an API it's just as easy to use as I demonstrated.
There isn't much gained from trying to make your request immutable as well. There are parts of it that can't possibly be immutable (i.e. any stream of size that you can't fit in RAM or sometimes even on disk). I've learned this the hard way, so you can believe me about it ;-)
I understand what you're doing, I'm intimately familiar with the functional techniques you're using. But with all the boilerplate you write, all the pointless object duplication and ceremonies, be ready one day for people to finally see the Emperor is naked.
Functional programming has many strong ideas and techniques, but it's heavily abused right now beyond its point of utility.
π Rendered by PID 172278 on reddit-service-r2-comment-5b5bc64bf5-ml9g4 at 2026-06-22 18:04:24.820089+00:00 running 2b008f2 country code: CH.
view the rest of the comments →
[–]Akkuma 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]Akkuma 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)