Skip to content

Bug: ParsedResultError contains nested ParseErrors instead of a ParseError with a cause of ZodError #3208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
marktowndrow opened this issue Oct 15, 2024 · 4 comments · Fixed by #3250
Assignees
Labels
bug Something isn't working completed This item is complete and has been merged/shipped parser This item relates to the Parser Utility

Comments

@marktowndrow
Copy link

marktowndrow commented Oct 15, 2024

Expected Behavior

In the following example:

const lambdaHandler = async (
  event: ParsedResult<JobsRequest>,
  context: Context
): Promise<APIGatewayProxyResult> => {

  if (!event.success) {
    return response(400, JSON.stringify((event.error.cause as ZodError).errors));
  }

  return response(200, `Parsed Event: ${JSON.stringify(event)}`);
};

const handler = middy(lambdaHandler).use(
  parser({ schema: jobsRequestSchema, envelope: ApiGatewayEnvelope, safeParse: true })
);

event.error.cause should contain a ZodError, and calling event.error.cause.errors should return something like:

[
    {
        "code": "too_small",
        "minimum": 0,
        "type": "number",
        "inclusive": false,
        "exact": false,
        "message": "ID must be positive",
        "path": [
            "id"
        ]
    }
]

Current Behavior

event.error.cause contains a ParseError, which contains another cause which contains the ZodError.

So to get to the ZodError, you have to call event.error.cause.cause

Code snippet

import { APIGatewayProxyResult } from "aws-lambda";
import { ApiGatewayEnvelope } from "@aws-lambda-powertools/parser/envelopes";
import { z } from "zod";
import middy from "@middy/core";
import { parser } from "@aws-lambda-powertools/parser/middleware";
import { ParsedResult } from "@aws-lambda-powertools/parser/types";

const response = (status: number, body: string): APIGatewayProxyResult => ({
  statusCode: status,
  body,
  headers: {
    "content-type": "application/json",
  },
});

const jobsRequestSchema = z.object({
  id: z.number().positive("ID must be positive"),
  from: z.coerce.date(),
  to: z.coerce.date(),
});

type JobsRequest = z.infer<typeof jobsRequestSchema>;

const lambdaHandler = async (event: ParsedResult<JobsRequest>): Promise<APIGatewayProxyResult> => {
  if (!event.success) {
    const errorResponse = {
      error_cause: event.error.cause,
      error_cause_cause: event.error.cause?.cause,
    };
    return response(400, JSON.stringify(errorResponse));
  }

  return response(200, `Hello World, Parsed Event: ${JSON.stringify(event)}`);
};

const handler = middy(lambdaHandler).use(
  parser({ schema: jobsRequestSchema, envelope: ApiGatewayEnvelope, safeParse: true })
);

module.exports = { handler };

POSTing the following body:

{
    "id": -1,
    "from": "2024-01-01",
    "to": "2024-01-02"
}

returns:

{
    "error_cause": {
        "name": "ParseError"
    },
    "error_cause_cause": {
        "issues": [
            {
                "code": "too_small",
                "minimum": 0,
                "type": "number",
                "inclusive": false,
                "exact": false,
                "message": "ID must be positive",
                "path": [
                    "id"
                ]
            }
        ],
        "name": "ZodError"
    }
}

Steps to Reproduce

Create a lambda with the above code in your handler.ts

Possible Solution

I haven't tested if this affects other Envelopes as well or not, but the apigw.ts safeParse function here

calls Envelope.safeParse(...) on line 30

and then creates a new ParseError on line 35, with the parsedBody.error as the cause.

parsedBody.error is itself already a ParseError from here on line 64, and that has the ZodError as its cause.

So depending on whether it affects all envelopes or not, we could maybe look at changing line 64 in envelope.ts to be error: parsed.error instead of creating a new ParseError with a cause?

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

18.x

Packaging format used

npm

Execution logs

No response

@marktowndrow marktowndrow added bug Something isn't working triage This item has not been triaged by a maintainer, please wait labels Oct 15, 2024
Copy link

boring-cyborg bot commented Oct 15, 2024

Thanks for opening your first issue here! We'll come back to you as soon as we can.
In the meantime, check out the #typescript channel on our Powertools for AWS Lambda Discord: Invite link

@am29d
Copy link
Contributor

am29d commented Oct 16, 2024

Hey @marktowndrow , thanks for raising the issue. As discussed in Discord, it should be a quick fix. You also narrowed down the code and explored the solution as well. If you want, you are more than welcome to make a PR, you are half way there. We have a set of tests for parser that you can use to verify your changes.

@am29d am29d added help-wanted We would really appreciate some support from community for this one confirmed The scope is clear, ready for implementation parser This item relates to the Parser Utility and removed triage This item has not been triaged by a maintainer, please wait labels Oct 16, 2024
@dreamorosi dreamorosi moved this from Triage to Backlog in Powertools for AWS Lambda (TypeScript) Oct 16, 2024
@am29d am29d self-assigned this Oct 22, 2024
@am29d am29d moved this from Backlog to Working on it in Powertools for AWS Lambda (TypeScript) Oct 23, 2024
@github-project-automation github-project-automation bot moved this from Working on it to Coming soon in Powertools for AWS Lambda (TypeScript) Oct 25, 2024
Copy link
Contributor

⚠️ COMMENT VISIBILITY WARNING ⚠️

This issue is now closed. Please be mindful that future comments are hard for our team to see.

If you need more assistance, please either tag a team member or open a new issue that references this one.

If you wish to keep having a conversation with other community members under this issue feel free to do so.

@github-actions github-actions bot added pending-release This item has been merged and will be released soon and removed help-wanted We would really appreciate some support from community for this one confirmed The scope is clear, ready for implementation labels Oct 25, 2024
Copy link
Contributor

This is now released under v2.11.0 version!

@github-actions github-actions bot added completed This item is complete and has been merged/shipped and removed pending-release This item has been merged and will be released soon labels Nov 20, 2024
@dreamorosi dreamorosi moved this from Coming soon to Shipped in Powertools for AWS Lambda (TypeScript) Nov 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working completed This item is complete and has been merged/shipped parser This item relates to the Parser Utility
Projects
Development

Successfully merging a pull request may close this issue.

2 participants