It is more of a generic question rather than Java-related as AWS API Gateway integration has nothing much to do with the language in which AWS Lambda function is written.
You can achieve returning custom error message by following the guidelines from the AWS documentation here: Handle Custom Lambda Errors in API Gateway
For Lambda custom integrations, you must map errors returned by Lambda in the integration response to standard HTTP error responses for your clients. Otherwise, Lambda errors are returned as 200 OK responses by default and the result is not intuitive for your API users.
There are two types of errors that Lambda can return:
- Standard Errors
- Custom Errors
In your API, you must handle these differently.
With the Lambda proxy integration, Lambda is required to return an output of the following format:
{
"isBase64Encoded" : "boolean",
"statusCode": "number",
"headers": { ... },
"body": "JSON string"
}
In this output, statusCode is typically 4XX for a client error and 5XX for a server error. API Gateway handles these errors by mapping the Lambda error to an HTTP error response, according to the specified statusCode. For API Gateway to pass the error type (for example, InvalidParameterException), as part of the response to the client, the Lambda function must include a header (for example, "X-Amzn-ErrorType":"InvalidParameterException") in the headers property.
For more details, check out this official document from AWS here: Handle Lambda Errors in API Gateway