0

I am writing an AWS Lambda Function.

and I would request the API without event.body for test

export const check = async (event) => {
  try{
    console.log("it does work");
    const {email, uid} = JSON.parse(event.body); // email and uid both would be undefined..
    //JSON.parse() throw some Error, so the below codes doesn't work.
    //Also, I can't see any single word from the response.
    if(!email && !uid) throw "No body data!"; // I expected throw this string but it didn't happend
    return {
      statusCode: 200,
      body: JSON.stringify({msg: "SUCCESS"})
    }
  }catch(e){
    return {
      statusCode: 500,
      body: JSON.stringify({e: e})
    }
  }
}

I could get this response.

{
  e: {}
}

I want to see

{
  e: "Some sentences about Error caused by JSON.parse() or No body data!"  
}

2 Answers 2

2

Try this:

  }catch(e){
    return {
      statusCode: 500,
      body: JSON.stringify({e: String(e)})
    }
  }

This will leave e as-is if it is already a string or convert it to a string containing the message if it is an Error object.

Sign up to request clarification or add additional context in comments.

Comments

1

To get the error message I believe you have to do it like this:

return {
  statusCode: 500,
  body: JSON.stringify({e: e.message})
}

Or, you can use Error.prototype.toString().

return {
  statusCode: 500,
  body: JSON.stringify({e: e.toString()})
}

Remember, e.message would be undefined for your the manually throw error (throw "No body data!";). In that case, you can check if e is a string. If string the use e otherwise e.message.

4 Comments

Could I block to pass the error from JSON.parse()?
You mean, you want to continue even if JSON.parse() throws an error?
Yes! I want to throw the error using my if-statements
@zynkn, the use another (nested) try-catch to handle only the JSON.parse().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.