I want to use a script to add domains from the DNS cache that match regular expressions to the address list.
However, the script is always interrupted by "no such item" error when reading DNS cache and on-error doesn’t work.
The code is wrong at the start, so obviously do error...
The best way to avoid making mistakes, or to prevent script from making them,
is...
to avoid making them.
{
:local regexp "theRegEx"
:local arrcache [:toarray ""]
:local arrlen 0
/ip dns cache
:set arrcache [find where name~$regexp]
:set arrlen [:len $arrcache]
:if ($arrlen = 0) do={:put ">$regexp< not found"}
:if ($arrlen = 1) do={:put "only one result found for >$regexp<"}
:if ($arrlen > 1) do={:put "($arrlen) results found for >$regexp<"}
}
Obviously there's a difference between "he finds only one" and "he finds many"... beyond the banal counting, otherwise I wouldn't have written it...
This piece of code, unless I've made some mistake,
simply can't cause any errors (unless the RouterOS syntax is changed, but the script should still be updated)...
So in this case there is no need for the stupid on-error-resume-next way of programming.
Yup, it could be the value of $arrcache is used elsewhere, and the "no such item" occurs later. Or since MikroTik is steering folks to use :onerror instead of the :do on-error=, perhaps there is an issue.
But agree with @rextended, just check the length, as that's definitive. Using on-error should be avoided as much as possible, especially when you can check :len or :typeof to avoid having errors.