Search code examples
javascriptd3.jsc3

c3.generate not throwing error


I'm using c3 + d3 + javascript to create a line chart in a webpage. I managed to create a code that was working fine locally, but when I uploaded it to my server, the code stopped working. I explain the problem below:

Problem: c3.generate is not throwing errors when uploaded to server

JSFiddle: http://jsfiddle.net/xq6wmyvp/10/

var chart;
function initialize(path) {
    try {
        c3.generate({
            bindto: '#chart',
            data: {
                x: 'label',
                url: path,
                type: 'line',
            },
            axis: {
                x: {
                    type: 'categories',
                    label: {
                        text: 'days',
                    },
                },
                y: {
                    label: {
                        text: 'yield',
                    },
                    tick: {
                        format: d3.format(".2%")
                    }
                }
            },
        });
    } catch (err) {
        return false;
    }
    return true;
}
var path1 = 'https://gist.githubusercontent.com/SamMorrowDrums/f571240047c0344a4af8/raw/433eae455570b64edcdc7ece39416b468b612f49/test.csv';
alert(initialize('blabla'));

Code explanation: the code (in the fiddle) has a function that initializes a chart with a line graph using some data. The path to the data is given as a variable to that function (which is called 'initialize(path)'). This function uses c3.generate to create the graph. If the data is not available or does not exist, c3.generate throws an error (this works locally, but not when uploaded to a server - this is the problem) and the function (initialize) returns false. If the data exists, the graph is loaded and 'initialize' returns true.

Problem Restated: after uploading the code to a server, the function 'initialize(path)' only returns 'true', even if the data is not available/non-existent.

I don't know how to solve this. Can you help me? Thanks for reading!

(Github link to problem: https://github.com/masayuki0812/c3/issues/960)


Solution

  • As I stated in my comment, under the hood c3 is using a d3.xhr to retrieve the data. This is an async call meaning that it's outside of your try block.

    Possible workarounds include:

    1.) fix it in the c3 source code At line 1903, you see the error is being dropped.

    2.) create a global error handler

    3.) don't use c3's url option. Issue your own d3 xhr request (handle the error the proper way there) and if successful, then call c3.generate with the columns option. This is the way I'd do it.

    d3.csv("path/to/file.csv", function(error, json) {
      if (error){
          // handle error properly
          return;
      }
      c3.generate({
        ...
      });
    });