In middleware, how to catch exception and return custom error code with body

The following does work:
setResponseStatus(422);
return { result: { error: "Validation error", status: 422 } } as any;

But, removing as any results in TypeScript error
Argument of type '({ next, data }: MiddlewareServerFnOptions<unknown, undefined, undefined>) => Promise<{ result: { error: string; status: number; }; } | undefined>' is not assignable to parameter of type 'MiddlewareServerFn<unknown, undefined, undefined, undefined, undefined>'.
  Type 'Promise<{ result: { error: string; status: number; }; } | undefined>' is not assignable to type 'ServerResultWithContext<undefined, undefined> | Promise<ServerResultWithContext<undefined, undefined>>'.
    Type 'Promise<{ result: { error: string; status: number; }; } | undefined>' is not assignable to type 'Promise<ServerResultWithContext<undefined, undefined>>'.
      Type '{ result: { error: string; status: number; }; } | undefined' is not assignable to type 'ServerResultWithContext<undefined, undefined>'.
        Type 'undefined' is not assignable to type 'ServerResultWithContext<undefined, undefined>'.ts(2345)
Was this page helpful?