rd
rd16mo ago

Error Handling vs Error Formatting

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!
3 Replies
rd
rd16mo ago
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;
}
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;
}
Nick
Nick16mo ago
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?
Yes I think you're doing it all right 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
rd
rd16mo ago
Great, thanks for clarifying!