There is a way to return an error inside catch without throw a new one?

I have a custom error that I call inside try. And I want to return this error inside catch without throw a new one.

const callSomething = async () => {
  try {
    doSomething();
  } catch (error) {
    // This function receive the error with the additional properties, so we need the custom error object
    customErrorTreatment(error);
  }
};

This function is where the error is first call.

const doSomething = async () => {
 try {   
    // This function throw a custom error class with additional properties
    throwApiError({
      responseMessage: 'Some error occour',
      responseStatus: 500,
    });
  } catch (error) {
    // If I return error, the function callSomething just receive the value without error.
    return error;

    // I can call throwApiError again, but feels ugly, that is the only way?
    return throwApiError({
      responseMessage: error.responseMessage
      responseStatus: error.status,
    });
  }
};

This is the custom error class and function

export const ApiError = class ApiError extends Error {
  constructor({ responseMessage, responseStatus, error }) {
    super(error);
    this.responseMessage = responseMessage;
    this.responseStatus = responseStatus;
  }
};
const throwApiError = ({ responseMessage, responseStatus, error }) => {
  throw new ApiError({ responseMessage, responseStatus});
};

8 thoughts on “There is a way to return an error inside catch without throw a new one?”

Leave a Comment