Error handling alternatives #465
-
Hello! I'm a big fan of oRPC, thanks for building it! I've been exploring error handling in oRPC and have some thoughts. In my applications I like to create my own set of custom error classes like so π Custom error classesimport type { Feature } from '@saas/authorization';
interface ApplicationErrorOptions {
userId?: string | null;
cause?: Error;
}
export abstract class ApplicationError extends Error {
protected userId: string | null = null;
constructor(
message: string = DEFAULT_ERROR_MESSAGES[
new.target.name as keyof typeof DEFAULT_ERROR_MESSAGES
],
options: ApplicationErrorOptions = {},
) {
super(message);
this.userId = options.userId ?? null;
this.cause = options.cause ?? null;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, new.target);
}
this.name = new.target.name;
}
getErrorInfo() {
return {
userId: this.userId,
errorType: this.name,
message: this.message,
stack: this.stack,
};
}
}
export const DEFAULT_SERVER_ERROR_MESSAGE = 'Something went wrong processing your request';
const DEFAULT_ERROR_MESSAGES = {
ForbiddenError: 'You do not have the required permission to do that',
NotFoundError: 'The requested item could not be found',
UnauthenticatedError: 'You must be logged in to do that',
FeatureAccessError: 'You do not have access to this feature',
} as const;
export class ForbiddenError extends ApplicationError {}
export class NotFoundError extends ApplicationError {}
export class UnauthenticatedError extends ApplicationError {}
export class FeatureAccessError extends ApplicationError {
constructor(feature: Feature) {
super(`You do not have access to the ${feature} feature`);
}
} The reason for this is that it makes it easy for me to throw what I know are user-friendly errors in my packages/applications and then I can propagate them to the client to show error messages. With the current oRPC approach to error handling it's a bit difficult to do this without tying myself to So my idea would is: what if we could specify a list of "propagated custom errors" that oRPC would know are fine to pass along intact to the client? As an alternative approach to Something like Thoughts? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Actually, we can do it now with |
Beta Was this translation helpful? Give feedback.
Ah, yes that's true... Thanks for the explanation. I put together an inbetween solution just so that I can map from my own errors to oRPC ones even when just calling actionables straight up. Here's what I came up with if anyone is interested:
Custom error -> oRPC error