Throwing custom exception in React

Viewed 36

So I have this function which sends request to the API and I want to throw exception when requests fails:

async function getCampaigns() {
        try {
            const response = await api.get('/cars');
            setSelectItems(
                response.map((item: Car) => ({
                    label: item.carLabel,
                    value: item.carValue
                }))
            );
            setLoading(false);
        } catch (error: any) {
            const exception = new Exception(error);
            exception.kind = 'recoverable';
            throw exception;
        }
}

I created custom exception to handle errors in this code:

Exception.ts

type ExceptionType = 'nonrecoverable' | 'recoverable';

export class Exception extends Error {
    public kind: ExceptionType;
    constructor(message?: string, options?: ErrorOptions) {
        super(message, options);

        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, Exception);
        }

        this.kind = 'nonrecoverable';
        this.name = 'Exception';
    }
}

However I am getting the following error whenever I get error response:

Unhandled Runtime Error
Exception: AxiosError: Request failed with status code 401

which is pointing at this line:

const exception = new Exception(error);

Not sure why is this happening and how can I throw the custom error like this?

EDIT:

So the actual problem here is that, when I catch the error and throw custom one based on the error caught I throw it again in the catch block. I think this results in the custom error that is being thrown uncaught. And because the custom error is uncaught, in Next.js development mode I get this error Overlay telling me about unhandled error...

Even though I have ErrorBoundary component that works as inteded (so redirects to the error component) but still Next.js overlay is displayed. So I am not sure how should I handle the custom error inside catch block in this situation? Is this correct approach already and should I leave it as it is or is there some better wayt to do this?

0 Answers
Related