DEV Community

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

Collapse
lukeshiru profile image
LUKESHIRU

Just to clarify a few things about JS:

About try...catch

You don't actually need to write a try...catch, you can just use promises directly:

app.get("/user", (request, response) =>
    dangerousDatabaseCall(request.userId)
        .then(response.send)
        .catch(() => response.status(400))
);
Enter fullscreen mode Exit fullscreen mode

And you can configure ESLint to have it check if you left any promise without a catch.

About switch...case

We don't have match in JS, but we have something pretty close:

const meal =
    {
        1: "Bulgogi",
        2: "Bibimbap"
    }[orderNumber] ?? "Kimchi Jjigae";
Enter fullscreen mode Exit fullscreen mode

About the point made against try..catch

I agree using try..catch is kinda nasty (I don't use it at all). But you have ways of not using it with JS as well:

readToString(`/assets/${request.pathToImageAsset}`)
    .then(rawImage => response.send(applySepiaFilter(rawImage)))
    .catch(() => response.status(400))
Enter fullscreen mode Exit fullscreen mode

One last thing, in JS you can also skip the return keyword if you're using an arrow function with a single expression: x => x * 2. Don't get me wrong, Rust is an amazing programming language, I just wanted to clarify that we have options in JS as well.

Cheers!