Error Handling vs Error Formatting

Bbongjovi4/24/2023
I'm a bit confused from the docs about how I should be handling errors on the server. The Error Handling section refers to handling errors client side right?

More specifically, the ORM I'm using suggests delegating error handling to the server implementation. Where the ORM is throwing an instance of its internal NotFoundError class, I need to update the response http code to 404 and also hide the data associated with that error in production. Should I be doing this within the errorFormatter?

Thanks!
Bbongjovi4/24/2023
e.g. I could do something like this, but I'm sure there is a better way? Like throwing a new TRPCError somewhere internally between my procedure and the formatter?

import { CustomOrmError, NotFoundError } from 'custom-orm';
import { TRPC_ERROR_CODES_BY_KEY } from '@trpc/server/dist/rpc';

const errorFormatter = ({ shape, error }) => {
  if (error.cause instanceof CustomOrmError) {
    if (error.cause instanceof NotFoundError) {
      return {
        message: 'Not found',
        code: TRPC_ERROR_CODES_BY_KEY['NOT_FOUND'],
        data: {
          code: 'NOT_FOUND',
          httpStatus: 404,
        },
      };
    }
    return {
      message: 'Something went wrong...',
      code: TRPC_ERROR_CODES_BY_KEY['INTERNAL_SERVER_ERROR'],
      data: {
        code: 'INTERNAL_SERVER_ERROR',
        httpStatus: 500,
      },
    };
  }
  return shape;
}
Nnlucas4/24/2023
Where the ORM is throwing an instance of its internal NotFoundError class, I need to update the response http code to 404 and also hide the data associated with that error in production. Should I be doing this within the errorFormatter?
Nnlucas4/24/2023
Yes
Nnlucas4/24/2023
I think you're doing it all right
Nnlucas4/24/2023
If you need to handle errors on the server, you can use a middleware to catch the DB's errors and then do whatever you need, then rethrow if you want the error to reach the frontend
Bbongjovi4/25/2023
Great, thanks for clarifying!