How to run a target specifically when an error occurs?
MSBuild has a special tag for this -- it's the only tag you can put under <Target> that doesn't represent a task. It's called
OnError.
Quick Example
Let's illustrate this with a simple example where we want to run the
SendMail target if and only if an error occurs in the Build target:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Build">
<Error Text="This simulates a build error. This task will return false from Execute()"/>
<OnError ExecuteTargets="SendFailureMail"/>
</Target>
<Target Name="SendFailureMail">
<Message Text="Sending failure mail"/>
</Target>
</Project>
Rules
- No tasks can follow an <OnError> tag in a target.
- You can have more than one <OnError> tag in a target: they'll be executed in order.
- Conditions are allowed.
- OnError tags form a stack: nested OnError tags will unwind outwards, and errors in targets called by OnError will execute any OnError tags in those targets. (I could explain this better couldn't I?)
- If a task error is masked with ContinueOnError="true", OnError will not be triggered.
- Once an error has occurred, the build cannot be prevented from aborting: but as it aborts, it will execute your OnError targets.