Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle api errors using aws-amplify?

I'm currently trying to POST data to my aws lambda functions triggered by aws api-gateway using the aws-amplify react lib.

Here is the code :

API.post("snippets","snippets/", {
        body: data,
    }).then(response => response).catch(console.log(err))

In the main case, everything is OK.

But my lambda function is design to validate the input data and return a status code 400 with a returned payload looking like that :

{
    "errors": [
        {
            "field": "title",
            "message": "This field is required"
        }
    ]
}

I would like to catch those errors in order to display them in the frontend but aws-amplify seems to have an undocumented behavior.

By default, status code 400 returned are throw with a default error message :

Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

Is there a way to get the returned payload instead of this magical error?

like image 316
Sébastien Le Gall Avatar asked Apr 03 '18 15:04

Sébastien Le Gall


People also ask

Does AWS amplify use API gateway?

The Amplify CLI deploys REST APIs and handlers using Amazon API Gateway and AWS Lambda.

What is API gateway error?

Handling API Gateway 502 Error: Bad Gateway A 502 error code is related to the service your API Gateway integrates with. It means that API Gateway couldn't understand the response. For example, when you throw an error in a Lambda function or the resolved value has an invalid structure, it can lead to a 502 error.

What is 4XX error in API gateway?

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 .


1 Answers

It turns out that under the hood, aws-amplifyuse Axios to make http calls.

When using Axios, you have to console.log(error.response): https://github.com/axios/axios/issues/960

Here is the fix I've made :

API.post("snippets","snippets/", {
        body: data,
    }).then(response => response).catch(error => console.log(error.response.data))

A Pull Request on the aws-amplify documentation is open : https://github.com/aws/aws-amplify/pull/633

like image 50
Sébastien Le Gall Avatar answered Sep 23 '22 08:09

Sébastien Le Gall