Say goodbye Trycatch Hell

Hi everyone! It is possible that it is here for the post title, and I daresay you have had problems handling errors with async/await. In this post you will learn a trick to avoid trycatch hell but before, it is neccessary to know a little history.


This content originally appeared on DEV Community and was authored by Ivan Zadivar

Hi everyone! It is possible that it is here for the post title, and I daresay you have had problems handling errors with async/await. In this post you will learn a trick to avoid trycatch hell but before, it is neccessary to know a little history.

History of Callback.

Once upon a time, developers had to deal with tasks that took a while, and the way we could check if the task was done was through callback.

Callbacks are nothing more than functions that are executed when a task has been completed, either erroneously or successfully. Until this moment, there is nothing bad. The problem arises when these callbacks in turn execute other functions, and so on. And that's when the macabre happens.

Animation Callback Hell

For this reason. Promise are born, as a solution to this problem.

Promises.

The promises are objects that represent the completion of a process, this can be a failure (reject) or a success (resolve). Also, lets add this beauty.

Comparation Promise vs Callback

Everything seemed magical, until...

Picture trycatch hell

Using async await makes the code more readable, it looks more beautiful, but it has a problem, is that if the promise fails, it will stop the flow of our system, so it is necessary to handle the errors.

But when handling these with trycatch we lose that readability, but don't worry, those are over now my dear friend.

How implemented.

First, we are going to simulate a whole. Let's do it.

We define some interfaces, and add test content.

interface Note {
  id: number;
  name: string;
}

interface Query {
  [key: string]: any;
}

const notes: Note[] = [
  {
    id: 1,
    name: "Megadeth",
  },
  {
    id: 2,
    name: "Korn",
  },
];

We define some functions.

async function update(id: number, data: Omit<Note, "id">, options: Query): Promise<Note> {
  const index: number = notes.findIndex(n => n.id === id);
  if (index < 0) throw new Error("Note does not exist");

  const updated: Note = { id, ...data };
  notes.splice(index, 1, updated);
  return updated;
};

async function remove(id: number, options: Query): Promise<Note> {
  const index: number = notes.findIndex(n => n.id === id);
  if (index < 0) throw new Error("Note does not exist.");

  const note: Note = notes[index];
  notes.splice(index, 1);
  return note;
};

We define our promise handler.

async function promHandler<T>(
  prom: Promise<T>
): Promise<[T | null, any]> {
  try {
    return [await prom, null];
  } catch (error) {
    return [null, error];
  }
}

Now, we only consume our handler.

  const [updated, err] = await promHandler(
    update(1, { name: "Mudvayne" }, {})
  );
  // updated -> {id: 1, name: "Mudvayne"}
  // err -> null

  const [removed, error] = await promHandler(remove(4, {}));
  // removed -> null
  // error -> Error "Does not exist."

Now I ask you, does it look better?

Perfect, we already know how to avoid trycatch hell, but this only using promises, what about synchronous functions?

Handling synchronous functions.

We convert our previous functions to synchronous.

function update(id: number, data: Omit<Note, "id">, options: Query): Note {
  // ...
};

function remove(id: number, options: Query): Note {
  // ...
};

We define our synchronous function handler.

function funcHandler<T extends any[], K>(
  func: (...args: T) => K,
  ...params: T
): [K | null, any] {
  try {
    return [func(...params), null];
  } catch (error) {
    return [null, error];
  }
}

We carry out the operations.

  const [updated, err] = funcHandler(update, 1, { name: "Mudvayne" }, {});
  // updated -> {id: 1, name: "Mudvayne"}
  // err -> null

  const [removed, error] = funcHandler(remove, 6, {});
  // removed -> null
  // error -> Error "Does not exist."

Great, we no longer have to struggle to make our code look more readable, and also, we reuse the handles.

You know, if you have something to contribute, a question, an improvement, you can contribute in the comments, and if it has been useful, leave your reaction, that makes me happy.


This content originally appeared on DEV Community and was authored by Ivan Zadivar


Print Share Comment Cite Upload Translate Updates
APA

Ivan Zadivar | Sciencx (2021-09-18T23:28:43+00:00) Say goodbye Trycatch Hell. Retrieved from https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/

MLA
" » Say goodbye Trycatch Hell." Ivan Zadivar | Sciencx - Saturday September 18, 2021, https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/
HARVARD
Ivan Zadivar | Sciencx Saturday September 18, 2021 » Say goodbye Trycatch Hell., viewed ,<https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/>
VANCOUVER
Ivan Zadivar | Sciencx - » Say goodbye Trycatch Hell. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/
CHICAGO
" » Say goodbye Trycatch Hell." Ivan Zadivar | Sciencx - Accessed . https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/
IEEE
" » Say goodbye Trycatch Hell." Ivan Zadivar | Sciencx [Online]. Available: https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/. [Accessed: ]
rf:citation
» Say goodbye Trycatch Hell | Ivan Zadivar | Sciencx | https://www.scien.cx/2021/09/18/say-goodbye-trycatch-hell/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.