← back to blog

i love rust's try catches

(less than a minute read)

alright, let's talk about something that fucks with me every time i write async code in javascript: try { } catch (e) {}. it isn't that useless, but i mean... it feels clunky and shit. the scoping is weird as shit, you end up nesting a shit ton of code, and half the time you're not even sure what kind of error you're catching. it's like javascript just hands you a mystery box and says “good fucking luck”.

meanwhile, over in rust, error handling actually makes sense. they use this thing called Result<T, E>, and it basically forces you to deal with both success and failure cases explicitly. it's clean, predictable, and best of all, it feels like part of the language -- not a random intern's project.

compare that to this classic javascript shit code:

try {
  const data = await doSomething();
  // do something else...
} catch (err) {
  // wait, what the fuck is this error?
}

now you've got a try-catch block, a floating variable scope, and code that gets messier the more logic you add. quite confusing.

so here's a little helper function that has made my life a whole lot easier:

export async function safePromise<T, E = Error>(
  promise: Promise<T>,
): Promise<{ data: T | null; error: E | null }> {
  try {
    const data = await promise;
    return { data, error: null };
  } catch (error) {
    return { data: null, error: error as E };
  }
}

now instead of writing try-catch blocks all over the place, I can just do this:

const { data, error } = await safePromise(fetchSomething());
 
if (error) {
  // handle the error properly
} else {
  // work with the data
}

way cleaner. no more random nested blocks. no weird scoping. and it just feels so much nicer to use. you might also recognize this from TanStack Query / React Query if you have ever used something like that.

is it as good as rust's Result type? not really but it's similar. it's one of those small things that makes your code easier to read, test, and maintain.

anyways, just wanted to share that. little random things like this here and there are pretty useful when trying to write javascript code.

thanks for reading this random rant, hope you have a decent day.