elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
10.35k stars 220 forks source link

Process Validation Error Code Mismatch: Incorrect Status Code for Any Thrown Error #882

Open K4leri opened 1 week ago

K4leri commented 1 week ago

What version of Elysia is running?

"elysia": "^1.1.22"

What platform is your computer?

Microsoft Windows NT 10.0.19045.0 x64

What steps can reproduce the bug?

import { Elysia, NotFoundError, t } from "elysia";

export const errorPlugin = new Elysia().onError(
  { as: "global" },
  ({ code, error }) => {
    console.log(code); // VALIDATION

    return { error };
  }
);
function decryptId(value: string) {
  if (value.length > 2) throw new NotFoundError(); // should give 404 status code, not 422
  return 1;
}
const transform = t
  .Transform(t.String())
  .Decode((value) => decryptId(value))
  .Encode((value) => `1`);

const aid = t.Object({
  aid: transform,
});
const activity = new Elysia().post(
  "activity/aid/:aid",
  ({ params, body, query }) => {
    console.log({ body: body.aid, query: query.aid, params: params.aid });
    const array = Array(10).fill({ aid: body.aid });
    return {
      data: array,
    };
  },
  {
    params: aid,
    body: aid,
    response: {
      200: t.Object({
        data: t.Array(t.Object({ aid: t.Integer() })),
      }),
    },
  }
);

const app = new Elysia()
  .use(errorPlugin)
  .use(activity)
  .listen(3000);

What is the expected behavior?

The expected behavior is that when a validation process throws an error, the correct HTTP status code corresponding to that error should be returned in .onError.

In this case, when a NotFoundError is thrown, the expected behavior is that a 404 HTTP status code should be returned, not a 422 status code.

What do you see instead?

Thrown errors during t.transform gives always 422 status code in .onError

Additional information

No response

Have you try removing the node_modules and bun.lockb and try again yet?

no

crishoj commented 1 week ago

throw new NotFoundError() in transform gives

crishoj commented 1 week ago

The issue seems to be that Typobox wraps the NotFoundError in a TransformDecodeError, so error.status is not picked up by app.handleError.

I took a stab at unwrapping the error in PR #885