Catching Policy Errors using FaultRules

2 0 586

Policies such as SQL Injection protection, quotas, and spike arrest throw a policy error if some condition is met. In this article, I will discuss how to catch a QuotaViolation policy error and then perform two steps: (1) log some information to a syslog target such as Loggly and (2) send the client a custom status code and reason phrase

Let's take a look at the default behavior when a Quota violation occurs. The Quota violation returns a status 500 Internal Server Error, and the response body looks like this:

582-screen-shot-2015-06-11-at-35830-pm.png

The response body, specifically the errorcode property, gives me the information I need to catch future Quota Violations.

The first thing I need to do is create a faultrule that performs 2 steps when a quota violation occurs. I define the faultrule in the "default" ProxyEndpoint as shown below. In the condition statement I am specifically catching the fault.name = "QuotaViolation" (which I retreived from the default errorcode property above). The first step executes the Log-Error policy which writes a custom message to Loggly or any other syslog target. The second step executes the Fault-Quota-Violation policy which raises a fault with a 429 status code.

581-screen-shot-2015-06-11-at-35059-pm.png

The Log-Error policy writes a message to Loggly using the MessageLogging policy. Within that policy, you can choose which request.variables you would like to include in the log message. My message includes the following:

<Message>[xxxx@yyy Reason={fault.name} APIKey={request.queryparam.apikey} developer={apigee.developer.email} clientip={client.ip} tag="{organization.name}.{apiproxy.name}.{environment.name}"]</Message>

The Fault-Quota-Violation uses the RaiseFault policy to change the status code to 429 and the Reason Phrase to "Too Many Requests"

<StatusCode>429</StatusCode> <ReasonPhrase>Too Many Requests</ReasonPhrase>

Hope this is useful!

Version history
Last update:
‎06-11-2015 04:28 PM
Updated by: