Amplify-js: Need to get my JSON response when API fails.

Created on 7 Oct 2019  路  2Comments  路  Source: aws-amplify/amplify-js

I'm using these in a React Native project:

    "amazon-cognito-identity-js": "^3.0.15",
    "aws-amplify": "^1.1.40",
    "aws-amplify-react-native": "^2.1.19",

In AWS, I've set up a REST API bound to a Lambda function. Here's my Lambda handler:

    return async event => {
      try {
        const response = await eventProcessor(event);
        return {
          statusCode: 200,
          body: JSON.stringify(response),
          headers
        };
      } catch (ex) {
        console.warn("ERROR", ex);
        return {
          statusCode: ex.statusCode || 400,
          body: JSON.stringify({message: ex.message || ex, code: ex.code || "INTERNAL_ERROR"}),
          headers
        };
      }
    };

On the React Native side, I have this:

import Amplify, {API, Auth} from "aws-amplify/lib/index";
...
      async create(myParams) {
        const params = {
          body: {myParams}
        };
        const result = await API.post(this.apiName, this.apiPath, params);
        return result.myObject;
      }

Everything works fine, except when the Lambda's "eventProcessor" throws an exception.
On the React Native side, I get an Error with this message: "Request failed with status code 400". I would like to get the actual error that I send back in the "body". Is there a way?

Thanks,
Alvaro

Cognito React Native to-be-reproduced

Most helpful comment

@alvaro1728, something like this maybe?

try {
  const result = await API.post(this.apiName, this.apiPath, params);
  return result.myObject;
} catch (e) {
  if (e.response.status === 400) {
    console.log(e.response.data); // Data contains your body
   }
}

All 2 comments

@alvaro1728, something like this maybe?

try {
  const result = await API.post(this.apiName, this.apiPath, params);
  return result.myObject;
} catch (e) {
  if (e.response.status === 400) {
    console.log(e.response.data); // Data contains your body
   }
}

@rafaponieman, that actually works. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

callmekatootie picture callmekatootie  路  3Comments

epicfaace picture epicfaace  路  3Comments

cosmosof picture cosmosof  路  3Comments

josoroma picture josoroma  路  3Comments

TheRealRed7 picture TheRealRed7  路  3Comments