Capturing Errors in MSBuild tasks
This may have been covered, but only stumbling upon this myself, I felt I would share it as it might help someone else out there. I will give the background first as it might provide valuable context.
I have been creating and automating our .NET build processes using MSBuild. MSBuild provides a great level of flexibility with how you can perform your builds but, it does lack in some areas. But the areas that it lacks in, thankfully the gap is filled by creating custom tasks and this has been the basis for some projects on CodePlex and mainly the MSBuild Extension Pack. This I believe fills almost all of the gaps that are missing from the normal tasks of MSBuild.
So, armed with all of these, I set out to create the the build.
- The build was performed as normal.
- I performed the compile of the deployment projects (which aren’t supported out of the box for MSBuild) by using the Exec command for devenv /build.
- Got the assembly file version using the MSBuild.ExtensionPack.Framework.Assembly and the GetInfo task.
- Created folders for the setup kit to be deployed to.
- Copied the MSI and setup.exe files to the deployment folders.
- Send email when all is well, using the MSBuild.ExtensionPack.Communication.Email and the Send task.
- Send email when process failed.
The emailing part was the main cause for concern for me. If everything worked, I got an email, this was what I had intended. If the compile fails, I also get an email, which is what I had intended. But, if steps 2 to 5 fail for any reason, I receive no email.
The reason for this is the email on the compile failed is in the target of BeforeOnBuildBreak which is where it should be as this target is only called when a build is broken.
So I need to capture the error. I did this by using the OnError task. Placed at the end of the task you are checking,
So, in the target if an error happens that is outside the compile process, will execute the target ParialSuccess. And with an aptly named <Target Name=”PartialSuccess”> and within is the MSBuild.ExtensionPack.Communication.Email.
Below is an example of what I mean.
So the AfterDropBuild is performed once the binaries have been put into the drop location. If any of these processes fail in this AfterDropBuild section, it will then transfer execution to the target to PartialSuccess. The emails I have provided here show also how one can reference the build details such as log files.
P.S I am sorry to those I tried to post the code on there directly but it seems that it was escaping all of the characters < > and others. So I created an XML file. This isn’t a complete project file, it is used just to show an example of sending emails when the non-compile process fails.