0

I have a very simple API in typescript and Nodejs, I'm experiencing a really weird problem where the "message" key on my error object is missing after creation.

This is the function that creates the error object, if I console.log, the message here is still present.

export function createNewError(status: number, message: string): customError {
    const err = new Error(message) as customError;
    err.error = message;
    err.message = getErrorMessageFromStatus(status);
    err.status = status;
    err.success = false;
    return err;
}

But right here where I'm calling the function, message is undefined. I'm calling it from a try catch block.

catch (caught: any) {
        const errorToSend = createNewError(
            statusCodes.INTERNAL_SERVER_ERROR,
            getErrorMessage(caught)
        );
        // Object.keys(errorToSend) => the message key is not present
        res.status(errorToSend.status).json(errorToSend);
        // so the client doesn't receive the full error
}

If I log the caught error, it is as expected. So nothing that could come from there. I am in fact receiving what is expected but not getting the expected outcome.

This error is only happening on one of my API routes, the update one, the rest of them deliver the actual error with the message key.

Here's the customError interface if it helps.

export interface customError extends Error {
  error: any;
  message: string;
  status: number;
  success: boolean;
}

And the getErrorMessageFromStatus function too.

export function getErrorMessageFromStatus(status: number): string {
    switch (status) {
        case statusCodes.BAD_REQUEST:
            return statusMessages.BAD_REQUEST;
        case statusCodes.UNAUTHORIZED:
            return statusMessages.UNAUTHORIZED;
        case statusCodes.FORBIDDEN:
            return statusMessages.FORBIDDEN;
        case statusCodes.NOT_FOUND:
            return statusMessages.NOT_FOUND;
        case statusCodes.INTERNAL_SERVER_ERROR:
            return statusMessages.INTERNAL_SERVER_ERROR;
        default:
            return statusMessages.INTERNAL_SERVER_ERROR;
    }
}

I've tried logging from inside the createCustomError function, and right before and after calling the function. Object.keys(errorToSend) doesn't show message as a key, console.log does show the expected message. I'm very confused and any help would be greatly appreciated.

Luis Ralda
  • 11
  • 1
  • _"here where I'm calling the function, message is undefined"_... there is no `message` in that part of your code so it's not clear what you mean – Phil Feb 21 '23 at 00:23
  • @Phil updated the code so it's easier to understand – Luis Ralda Feb 21 '23 at 01:22
  • It's the same issue as the suggested duplicate. `Error` does not have enumerable keys – Phil Feb 21 '23 at 01:24

0 Answers0