kiewic
kiewic

Reputation: 16450

How to handle `Error: invalid value for <path> attribute d="waaa"` in d3.js?

How can I catch or know if an error occurs when setting an invalid d value for a svg/path node?

I tried to wrap the call with try/catch, but that is not working:

try {
    dotArray[i][j] = dotG
        .append('path')
        .attr('d', 'waaa');
}
catch (error) {
    console.log('error handled');
}

The catch is never executed. Does d3.js swallow the errors?

Upvotes: 2

Views: 650

Answers (2)

Mark
Mark

Reputation: 108567

My understanding is that this is a browser SVG parser error and not a JavaScript error. It does not raise a JavaScript exception because the JavaScript functions just fine.

If you need to test the validity of a path you could do something like:

var body = d3.select('body');

var svg = body
        .append('svg')
        .attr('width', 0)
        .attr('height', 0);

var d1 = "NotaRealPath";
var d2 = "M0,0L100,100";

var path1 = svg.append('path')
  .attr('d', d1);

var path2 = svg.append('path')
  .attr('d', d2);

// is there any path data to parse here?
var isError1 = path1.node().pathSegList.length === 0;
var isError2 = path2.node().pathSegList.length === 0;


document.write(!isError1 ? "Good Path: " + d1 : "Bad Path: " + d1);
document.write("<br>");
document.write(!isError2 ? "Good Path: " + d2 : "Bad Path: " + d2);
<script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>

Upvotes: 1

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

The error isn't generated by the Javascript code, but by the browser's rendering code. That is, the code you've written is perfectly valid, but the values you set cannot be interpreted by the browser.

As far as I know, there's no way to catch such errors in Javascript as the Javascript code executes fine.

Upvotes: 0

Related Questions