Skip to content
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

Support customizing an error response body #440

Open
rhinodavid opened this issue Feb 28, 2024 · 0 comments
Open

Support customizing an error response body #440

rhinodavid opened this issue Feb 28, 2024 · 0 comments

Comments

@rhinodavid
Copy link

trpc-openapi is opinionated about the body of error responses:

 const body: OpenApiErrorResponse = {
        message: isInputValidationError
          ? 'Input validation failed'
          : errorShape?.message ?? error.message ?? 'An error occurred',
        code: error.code,
        issues: isInputValidationError ? (error.cause as ZodError).errors : undefined,

There is an ability to customize the message for errors which don't throw from input validation, but no ability to modify the body otherwise.

I'm trying to convert an existing express-only server to use tRPC with trpc-openapi so we get the TypeScript client, autogen'd docs, etc.

The problem I'm running into is that we currently return a property reason in the error response body, and unfortunately there is a requirement to maintain this behavior.

Right now this is possible, but it's nasty.

For the onError argument I'm hijacking the NodeHTTPResponse end function:

const openApiMiddleware = createOpenApiExpressMiddleware({
    onError: ({ error, req }) => {
        const res = req.res;
        if (!res) return;

        const originalEndFn = res.end;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const overrideEndFn: typeof res.end = (arg1: any, arg2?: any, arg3?: any) => {
            console.log('Original error was', inspect(error));
            if (typeof arg1 === 'string') {
                const bodyOverride = {
                    message: "fail",
                    reason: "FOR_REASONS",
                };
                return originalEndFn.call(res, JSON.stringify(bodyOverride), arg2, arg3);
            }
            return originalEndFn.call(res, arg1, arg2, arg3);
        };
        res.end = overrideEndFn;
    },
    router,
});

I'm wondering if you would be open to PRs to enable more error customization. The change would probably involve making onError return a body and status code. I'm not sure how this would affect the openApi spec generation, or how exactly it would interact with responseMeta, but I'm sure we could figure out details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant