DEV Community

Discussion on: Callbacks vs Promises in JavaScript

 
aminnairi profile image
Amin • Edited

I understand what you are trying to do. You could use custom Error subclasses which allow you to keep handling errors in the catch part while still having some control over which kind of error is thrown instead of a generic one.

"use strict";

class PostResponseError extends Error {
    constructor(...parameters) {
        super(...parameters);

        this.name = "PostResponseError";
    }
}

class UserResponseError extends Error {
    constructor(...parameters) {
        super(...parameters);

        this.name = "UserResponseError";
    }
}

async function main() {
    try {
        const url = "https://jsonplaceholder.typicode.com";
        const postResponse = await fetch(`${ url }/posts/1`);

        if (!postResponse.ok) {
            throw new PostResponseError("Error with the response");
        }

        const post = await postResponse.json();
        const userResponse = await fetch(`${ url }/users/${ post.userId }`);

        if (!userResponse.ok) {
            throw new UserResponseError("Error with the response");
        }

        const user = await userResponse.json();

        console.log("User who has posted the first post");
        console.log(user);
    } catch (error) {
        if (error instanceof PostResponseError) {
            console.log("Error with the post response");
        } else if (error instanceof UserResponseError) {
            console.log("Error with the user response");
        } else {
            console.error("Unexpected error");
        }

        console.error(error);
    }
}

main();
Thread Thread
 
wichopy profile image
Will C.

Beautiful 😍