Effect CommunityEC
Effect Community2y ago
39 replies
addamsson

Can Case Classes Have Default Values and Implement Interfaces?

I'm looking at the Case Classes documentation and I was wondering if it is possible to have default values / implementations and/or to extend / implement an interface when using them?
This is what I had previously:
export type ProgramError = {
    __tag: string;
    /**
     * A human-readable message describing the error that is safe
     * to propagate to the end user.
     */
    message: string;
    /**
     * An error message that is intended to inform the developer
     * about the error conditions. This message should be logged.
     */
    debugMessage: string;
    cause?: ProgramError;
};

export abstract class ProgramErrorBase<T extends string>
    extends Error
    implements ProgramError
{
    public override message: string;
    public override cause: ProgramError | undefined;
    public debugMessage: string;

    public __tag: T;

    constructor(params: {
        __tag: T;
        message: string;
        debugMessage?: string;
        cause?: ProgramError;
    }) {
        const { __tag, message, debugMessage, cause } = params;
        super(params.message);
        this.__tag = __tag;
        this.message = message;
        this.debugMessage = debugMessage ?? message;
        this.cause = cause;
    }
}

and this is how I used it to implement an error:
export class JobStorageError extends ProgramErrorBase<"JobStorageError"> {
    constructor(cause: unknown) {
        super({
            __tag: "JobStorageError",
            message: `Failed to store job. Cause: ${cause}`,
        });
    }
}

new JobStorageError("whatever);

I really like the simplicity of case classes but it would be great to define a type for the common fields (message and debugMessage here), and to be able to provide default values like Failed to store job. Cause: ${cause}. Is this possible with case classes somehow? What's the best practice when creating error objects like this above?
Was this page helpful?