DEV Community

Discussion on: Ditching try...catch and null checks with Rust

Collapse
phlash909 profile image
Phil Ashby

Thank you for this excellent demonstration of Rust safety through strongly-typed errors and avoiding null :)

How do you think this compares to JS promises, which appear to offer a similar wrapper-based approach to error handling, and co-incidentally deferred execution, or Golang error type?

Collapse
lukeshiru profile image
LUKESHIRU • Edited

The first example showcased in this post is using promises, but just with syntax sugar on top of it. The following two are exactly the same with different syntax:

// Scenario 1: catching a dangerous database call
app.get("/user", async function (req, res) {
    try {
        const user = await dangerousDatabaseCall(req.userId);
        res.send(user);
    } catch (e) {
        // couldn't find the user! Time to tell the client
        // it was a bad request
        res.status(400);
    }
});
Enter fullscreen mode Exit fullscreen mode
// Scenario 1: catching a dangerous database call
app.get("/user", (req, res) =>
    dangerousDatabaseCall(req.userId)
        .then(user => {
            res.send(user);
        })
        // couldn't find the user! Time to tell the client
        // it was a bad request
        .catch(e => {
            res.status(400);
        })
);
Enter fullscreen mode Exit fullscreen mode