You can use the event UI_ERROR_MESSAGE for this case! I have a script on classic that auto dismounted when attacking or opening a flight path up, but I can't recall if it handled the case of mining or not as well. I don't have a sub active for WoW currently, but looking at this (or what Seerah posted) might help you get a start
Pastebin link