Internal server error on try-catch

Hello, I’m experiencing a 500 response when I try to do a try-catch block I’m not sure why.

In the past, I used MongoDB on NodeJS so I always have the error.
The way the MongoDB driver works for Java is quite different, for example when I use insertOne, the documentation says:

 * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the insert command
 * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
 * @throws com.mongodb.MongoException             if the write failed due some other failure

so I try to do:

override fun handleRequest(input: Map<String, Any>, context: Context): ApiGatewayResponse {
    return try {
        getMeasuresCollection()
                .insertOne(Measure(
                        12312312L,
                        "blood",
                        hashMapOf("a" to 3f),
                        hashMapOf("a" to "oh my")))

        ApiGatewayResponse.build {
            statusCode = 200
            objectBody = HelloResponse(true, null)
            headers = mapOf("X-Powered-By" to "AWS Lambda & serverless")
        }
    } catch (exception: Exception) {
        ApiGatewayResponse.build {
            statusCode = 200
            objectBody = HelloResponse(false, exception)
            headers = mapOf("X-Powered-By" to "AWS Lambda & serverless")
        }
    }
}

that hangs my app for 6 seconds and returns an Internal Server Error.

But if I don’t use try-catch:

override fun handleRequest(input: Map<String, Any>, context: Context): ApiGatewayResponse {
    
    getMeasuresCollection()
            .insertOne(Measure(
                    12312312L,
                    "blood",
                    hashMapOf("a" to 3f),
                    hashMapOf("a" to "oh my")))
    
    return ApiGatewayResponse.build {
        statusCode = 200
        objectBody = HelloResponse(true, null)
        headers = mapOf("X-Powered-By" to "AWS Lambda & serverless")
    }
}

I get my response.

What is happening?

When I got 500 error, I always try to look lambda log.
Cheers,
John

1 Like

I’m going to put my solution since I didn’t find it somewhere else.

Someone talked about this, but not directly from this error.
The error was due to timeout, but it didn’t specify why.

It looks like the first time you deploy, you need to call that function to “unfreeze” it. The first time you call that function it takes between 6000ms and 10000ms (depends on the function) but Amazon sets the default timeout at 6 seconds, so sometimes you’re never able to “unfreeze” the function.

Said that, you need to set a timeout, at least to 30 secs and the error will be gone.

1 Like

Yes, that is right. Thanks for the sharing @rafaelruizmunoz