Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handling Service Errors in OCI CLI

Handling Service Error with OCI CLI can be a bit cumbersome but still possible.

Let's take the following example:

$ response=$(oci os object put -ns my-ns -bn my-bucket --file my-file --query etag --raw-output)
Uploading object [####################################] 100%ServiceError:
{
"code": "BucketNotFound",
"message": "Either the bucket named 'my-bucket' does not exist in the namespace 'my-ns' or you are not authorized to access it",
"opc-request-id": "fra-1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"status": 404
}

The response variable will be empty...

The problem is that the Service Error message goes to the standard error and is not processed by JMSPath. The good thing is that the oci command returns a non zero error code and error conditions can be trapped.

Here is a simple example on what you could do for this particular case, assuming you want to print the error message:

#!/usr/bin/env bash
# stderr needs to be redirected as well!
response=$(oci os object put -ns my-ns -bn my-bucket --file my-file --query etag --raw-output 2>&1)
# Check the return code
if [[ $? == 0 ]]; then
  # All went well!
  echo "File uploaded, etag: ${response}"
else
  # Handle error
  if [[ ${response} =~ ServiceError ]]; then
    # we have a Service Error, only keep the JSON part of the response and
    # use JQ to parse it:
    message=$(grep -Pzo "(?s){.*}" <<<${response} | jq -r .message)
    echo "Service Error: ${message}"
  else
    # Other error...
    echo "Unexpected error message: ${response}"
  fi
fi

Running the above script gives:

$ ./demo.sh
Service Error: Either the bucket named 'my-bucket' does not exist in the namespace 'my-ns' or you are not authorized to access it

As such the above example is probably useless, but it should help you building your own handler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.