simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

improveErrorMessage.js (1150B)


      1 import { typeOf } from '../../../utils/is.js';
      2 /**
      3  * Improve error messages for statistics functions. Errors are typically
      4  * thrown in an internally used function like larger, causing the error
      5  * not to mention the function (like max) which is actually used by the user.
      6  *
      7  * @param {Error} err
      8  * @param {String} fnName
      9  * @param {*} [value]
     10  * @return {Error}
     11  */
     12 
     13 export function improveErrorMessage(err, fnName, value) {
     14   // TODO: add information with the index (also needs transform in expression parser)
     15   var details;
     16 
     17   if (String(err).indexOf('Unexpected type') !== -1) {
     18     details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')';
     19     return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details);
     20   }
     21 
     22   if (String(err).indexOf('complex numbers') !== -1) {
     23     details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : '';
     24     return new TypeError('Cannot calculate ' + fnName + ', no ordering relation is defined for complex numbers' + details);
     25   }
     26 
     27   return err;
     28 }