To can I reference the error code of a failed step in an Azure pipeline

45 views Asked by At

I need an Azure pipeline to check the error code that caused a previous step to fail. The failed step uses an Azure plugin that can return various error codes based on what caused the step to fail, and I need the next step to take different actions based on the specific return code. If the failed step was a script, I would just set a pipeline variable based on the return code, but I'm unable to do this with the plugin-based task. How can I get the next step to check the return code of the previous step?

1

There are 1 answers

0
Miao Tian-MSFT On

You can use the REST API Timeline - Get in the pipeline to get the detail of the task.

My test example:

trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:
- script: |
    echo Hello, world!
    exit 2
  name: ProduceError
  continueOnError: true

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $url = "https://dev.azure.com/{orgname}/{project}/_apis/build/builds/$(Build.BuildId)/timeline?api-version=7.1"
      $response = Invoke-RestMethod -Uri $url -Headers @{
        "Authorization" = "Bearer $(System.AccessToken)"
      }
      
      #The record of task "ProduceError"
      $data = $response.records | Where-Object { $_.name -eq "ProduceError" } | ConvertTO-Json
      $data  
      $errorCodeMessage = $response.records | Where-Object { $_.name -eq "ProduceError" } | Select-Object -ExpandProperty issues | Select-Object -ExpandProperty message
      
      #the next step to take different actions based on the specific error Code Message
      if ($errorCodeMessage -match "1") {
        write-host "errorCodeMessage is $errorCodeMessage"
      } elseif ($errorCodeMessage -match "2") {
        write-host "errorCodeMessage is $errorCodeMessage"
      } else {
        write-host "errorCodeMessage is $errorCodeMessage"
      }

In this sample, the first task name is ProduceError, then we can get the record of the task in the PowerShell task with the REST API.

Test result:

enter image description here

enter image description here