I wrote a small function to cascade errors in React & React Native with TypeScript:
/** * Function that takes an error and trow an enriched error * @param error the original error * @param func the name of the function trowing the error * @param params the parameters passer to the function * @param custom a custom message to add* * @returns an enriched error */const throwR = (error: Error, func?: string, params?: any, custom?: string) => { // Parse params in an human readable form let parsedParams: string = '' if (params && typeof params === 'object') { try { parsedParams = JSON.stringify(params) } catch (err) { parsedParams = `${params.toString()} (JSON.stringify returned: ${err})` } } else { try { parsedParams = params.toString() } catch (err) { parsedParams = `<params.toString(): ${err}>` } } // Handle the case where no error message is provided if (!error) { try { console.log(`on ${func}(${parsedParams})${''+ custom}: No error message provided to throwR`) } catch (err) { console.log(`No error message provided to throwR and unable to build this message: ${err}`) } } // build the error message let message: string = '' try { message = `on ${func}(${parsedParams})${''+ custom}: ${error}` } catch (err) { message = `${error} (could not build enriched message: ${err})` } // build the new error const newError = new Error(message) // add the original error name try { newError.name = error.name } catch (err) { console.log(`on throwR, could not add a name to the error: ${error}`) } // by the end, throw the error throw newError}export default throwR
Then I use it with:
const myFunction(params) => { try { // potentially faulty code } catch (error) { throwR(error, 'myFunction', params, 'custom message') }}
I went on forums and saw that most people were using a custom error class then:
const myFunction(params) => { try { // potentially faulty code } catch (error) { throw new CustomError(error, customParameter) }}
I'm a begineer and don't yet understand well the implication of each method. I would like to avoid a big pitfall that would later mean that I need to refactor all my code.
Could you explain me the implications of each approach and point me to a correct method for custom errors and cascading errors?
Thanks