Customizing error responses returned by AWS API Gateway
TypeScriptCustomizing error responses in AWS API Gateway allows you to control the output that your users receive when an error occurs. You might want to do this for several reasons, such as providing more informative messages, masking internal information, or complying with your API's specific format.
AWS API Gateway lets you set up custom error responses by configuring the Integration Response and Method Response settings. Integration Responses allow you to map backend responses to your desired HTTP status codes and messages. Method Responses specify the status codes, headers, and body formats that the client is allowed to receive.
To begin with, we create an instance of the REST API, after which we define a Resource (like
/error
) and a Method (likeGET
). Then, we customize the Integration Response to include a specific message or status code when a particular pattern in the backend response is matched. This could be a regex pattern that identifies error messages from your backend service.In the following program written in TypeScript, we set up a simple REST API with AWS API Gateway with a custom error response:
import * as pulumi from '@pulumi/pulumi'; import * as aws from '@pulumi/aws'; // Creating an instance of AWS API Gateway REST API. const api = new aws.apigateway.RestApi('myApi', { description: 'This is my API for demonstration purposes', }); // Creating a resource under the API, e.g., /error const resource = api.root.addResource('error', { pathPart: 'error', }); // Creating a GET method for the /error resource const method = resource.addMethod('GET', new aws.apigateway.MockIntegration({ integrationHttpMethod: 'POST', passthroughBehavior: 'WHEN_NO_MATCH', requestTemplates: { 'application/json': "{\"statusCode\": 500}" }, type: 'MOCK', }), { methodResponses: [{ statusCode: '500', responseModels: { 'application/json': 'Error', }, }], }); // Customizing the integration response to return a custom error message and status code new aws.apigateway.IntegrationResponse('myIntegrationResponse', { restApi: api.id, resourceId: resource.id, httpMethod: method.httpMethod, statusCode: '500', responseTemplates: { 'application/json': JSON.stringify({ message: 'An error occurred', }), }, selectionPattern: '5\\d{2}', // matching status code starting with a '5' e.g., 500, 502 etc. }); // Export the HTTP endpoint of the REST API export const url = api.executionArn.apply(arn => `https://${arn}.execute-api.${aws.config.region}.amazonaws.com/${resource.path}`);
In this program, we create a new
aws.apigateway.RestApi
to deploy a REST API. A resource at/error
is then added, where we can simulate an error response. We then create aGET
method for this resource with a mock integration, usingaws.apigateway.MockIntegration
, as we just want to simulate a response for demonstration.Next, the
aws.apigateway.IntegrationResponse
resource configures the Integration Response with a custom message and a pattern to catch 5xx errors (like 500 internal server error, 502 bad gateway, etc.). TheselectionPattern
is set to a regex value that matches any 5xx status code. TheresponseTemplates
attribute allows us to customize the body of the error response.Finally, we export the URL of the API to be accessed publicly.
When a client accesses
/error
on this API Gateway instance, they will receive a response with status code 500 and a custom error message specified in theresponseTemplates
configuration. This way, you can offer better error handling and make the responses from your API more meaningful for the consumers.