jeudi 29 juin 2017

Are try-catch meant to prevent or handle errors? (in javascript)

Recently I had a discussion with my coworker, about using try and catch to notify errors or avoid them.

This is my coworker's approach:

import Config from 'config';

export const getUserFromLocalStorage = () => {
  const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);

  try {
    return key ? JSON.parse(localStorage[key]) : {};
  } catch (e) {
    return {};
  }
};

Wich means, he doesn't care about the given error and he is just carrying of returning an object in order to continue the process

and mine is:

import Config from 'config';

export const getUserFromLocalStorage = () => {
  const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);

  try {
    return key ? JSON.parse(localStorage[key]) : {};
  } catch (e) {
    alert('something went wrong!'); // Just simple notifier for this example
    console.log('the given error', e); // Just simple notifier for this example
  }
}; 

but my approach, still has a problem which is that it will return undefined (which can crash internaly my app), that can easily fix it using finally and returning a default value but it doesn't sound a good practice to me.


THE QUESTION

So what will the balance using try catch and finally if needed, to make my application stable.
Is there something wrong with our approach?
In particular, we can't trust the data that is comming from the localStorage, so what will be the best approach for this implementation?




Aucun commentaire:

Enregistrer un commentaire