Difficult question - first what do you mean with shutdown? Does printer have a controllable power plug or something like that?
Then it really depends much on printer firmware and how it signals error. On serious errors we stop a running print, so if what you want is some action when a print stops due to an error, just add your action to "Run if job is aborted" also this means to stop when you hit stop button.
An other solution is to check the message of your firmware and add the action in "Replacements" gcode where you monitor for a serious error. E.g. marlin error messages start with "Error:" or have the word "kill() called" or start with !! - depends a bit on version and fork.