Skip to content

Instantly share code, notes, and snippets.

@bytekast
Created December 7, 2017 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bytekast/05d62ed11106920e8f9257196967cf56 to your computer and use it in GitHub Desktop.
Save bytekast/05d62ed11106920e8f9257196967cf56 to your computer and use it in GitHub Desktop.
Common Base Handler for Lambda Functions
package com.stedi.platform.lambda
import com.amazonaws.services.lambda.runtime.Context
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.codehaus.groovy.runtime.StackTraceUtils
@Slf4j
@CompileStatic
abstract class AbstractEventHandler implements CommonTrait, AmazonSNSTrait, DataDogTrait, SentryTrait {
void eventHandler(Map input, Context context) {
try {
final RequestContext requestContext = new RequestContext(input, context)
LambdaRequest.instance.set(requestContext)
// Log to Sentry
breadcrumb(requestContext.jsonRequest())
// Return immediately if keep alive request
if (input?.keepAlive?.toString()?.toBoolean()) {
return
}
try {
// Process request
this.handleEvent(requestContext)
return
} catch (e) {
reportError(requestContext, e)
return
}
}
finally {
LambdaRequest.instance.remove()
}
}
private void reportError(RequestContext requestContext, Throwable t) {
def rootCause = StackTraceUtils.extractRootCause(t).message
log.error(rootCause, StackTraceUtils.sanitize(t)) // Send to Sentry on log.error
try {
// Send error to DataDog if topic exists
if (env('MONITOR_TOPIC_ARN')) {
def error = buildErrorEventJson(requestContext.context, "${this.class.simpleName} - ${rootCause}", stackTrace(t))
publish(env('MONITOR_TOPIC_ARN'), error)
}
// Send to DLQ if topic exists
if (env('ERROR_TOPIC_ARN')) {
publish(env('ERROR_TOPIC_ARN'), requestContext.body() ?: toJson(snsJsonBody(requestContext.input)))
log.info "Sent original payload to error topic: ${env('ERROR_TOPIC_ARN')}"
}
}
catch (e) {
log.error(StackTraceUtils.extractRootCause(e).message, StackTraceUtils.sanitize(e)) // Send to Sentry on log.error
}
}
// Subclass must implement this
abstract void handleEvent(final RequestContext requestContext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment