

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 的自訂回應範例 AWS SAM
<a name="serverless-controlling-access-to-apis-customize-response"></a>

您可以在 AWS SAM 範本中定義回應標頭，以自訂一些 API Gateway 錯誤回應。若要這樣做，您可以使用[閘道回應物件](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#gateway-response-object)資料類型。

以下是為`DEFAULT_5XX`錯誤建立自訂回應的範例 AWS SAM 範本。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      GatewayResponses:
        DEFAULT_5XX:
          ResponseParameters:
            Headers:
              Access-Control-Expose-Headers: "'WWW-Authenticate'"
              Access-Control-Allow-Origin: "'*'"
              ErrorHeader: "'MyCustomErrorHeader'"
          ResponseTemplates:
            application/json: "{\"message\": \"Error on the $context.resourcePath resource\" }"
              
  GetFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.10
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
          raise Exception('Check out the new response!')
      Events:
        GetResource:
          Type: Api
          Properties:
            Path: /error
            Method: get
            RestApiId: !Ref MyApi
```

如需 API Gateway 回應的詳細資訊，請參閱[《 API Gateway 開發人員指南](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html)*》中的 API Gateway* 回應。