/*
 * Copyright 2015 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.netflix.spinnaker.kork.aws;

import com.amazonaws.*;

public class AwsMetricsSupport {
  static String[] buildExceptionTags(AmazonWebServiceRequest originalRequest, Exception exception) {
    final AmazonServiceException ase = amazonServiceException(exception);

    return new String[] {
      "requestType", originalRequest.getClass().getSimpleName(),
      "statusCode", Integer.toString(ase.getStatusCode()),
      "errorCode", ase.getErrorCode(),
      "serviceName", ase.getServiceName(),
      "errorType", ase.getErrorType().name()
    };
  }

  static AmazonServiceException amazonServiceException(Exception exception) {
    return amazonServiceException(exception, "UNKNOWN", -1);
  }

  static AmazonServiceException amazonServiceException(Exception exception, String serviceName, int statusCode) {
    if (exception instanceof AmazonServiceException) {
      return (AmazonServiceException) exception;
    }

    final AmazonServiceException ase = new AmazonServiceException(exception.getMessage(), exception);
    ase.setStatusCode(statusCode);
    ase.setErrorCode("UNKNOWN");
    ase.setServiceName(serviceName);
    ase.setErrorType(AmazonServiceException.ErrorType.Unknown);
    return ase;
  }
}

@@ -656,16 +656,44 @@
 aws.*;%0A%0A
+import java.util.Optional;%0A%0A
 public c
@@ -717,16 +717,76 @@
 pport %7B%0A
+  private static final String DEFAULT_UNKNOWN = %22UNKNOWN%22;%0A%0A
   static
@@ -1126,107 +1126,267 @@
 e%22, 
-ase.getErrorCode(),%0A      %22serviceName%22, ase.getServiceName(),%0A      %22errorType%22, ase.getErrorType(
+Optional.ofNullable(ase.getErrorCode()).orElse(DEFAULT_UNKNOWN),%0A      %22serviceName%22, Optional.ofNullable(ase.getServiceName()).orElse(DEFAULT_UNKNOWN),%0A      %22errorType%22, Optional.ofNullable(ase.getErrorType()).orElse(AmazonServiceException.ErrorType.Unknown
 ).na
@@ -1525,25 +1525,31 @@
 eption, 
-%22
+DEFAULT_
 UNKNOWN
-%22
 , -1);%0A 
@@ -1935,25 +1935,31 @@
 rorCode(
-%22
+DEFAULT_
 UNKNOWN
-%22
 );%0A    a

Add some defensive checks around spectator tag generation for AWS backoff/retry instrumentation