I am working on a web tool, which lets you change attributes of SVG elements. Currently I am trying to give the user feedback on any invalid attributes or values.
When calling setAttribute (or setAttributeNS) on an SVG element with an unexpected value, a javascript error occurs. I tried to catch this by using try/catch or window.onerror, but could not find a way to do so.
Example code:
<svg id="svg" width="300" height="100">
<linearGradient id="gradient" x1="10" y1="10" x2="100" y2="100">
<stop offset="0" stop-color="#000000"></stop>
<stop offset="1" stop-color="#969695"></stop>
</linearGradient>
</svg>
try {
document.querySelector('#gradient').setAttribute('x1', 'This error is not catchable');
} catch (error) {
console.log('never triggered');
}
https://jsfiddle.net/wr3tne2y/
tested in Chromium v91 and firefox:
You would need to check the value before setting it.
let val = 'This error is not catchable';
if (!isNaN(parseInt(val, 10)))
{
document.querySelector('#gradient').setAttribute('x1', val);
}
else
{
console.log('ERROR!');
}