DEV Community

loading...

A quick trick for cleaner code

apes
Updated on ・1 min read

If you're using a REST API for your backend data you probably have some code like this:

get_request("/posts/" + id + "/comments")
    .then(action(resp => {
        this.requestInProgress = false;

        if (resp.error) {
            this.error = resp.error.message;
        } else {        
            this.post = new PostModel(resp.post);
        }
    }))

Which does the job. But it doesn't deal with things like network errors or other more serious errors that mean your .then function is never reached.

So, rather than writing error handling in your if statement and in your catch statement, it's much more verbose to just throw the error in then and put all your error handling in .catch.

get_request("/posts/" + id + "/comments")
    .then(action(resp => {
        this.requestInProgress = false;
        if (resp.error)
            throw new Error(resp.error.message);

        this.post = new PostModel(resp.post);
    }))
    .catch(action(err => {
        this.requestInProgress = false;
        this.error = err.toString();
    }));

You can even take it further and add it to the function you're using for requests:

fetch(SERVER_BASE_URL + url, {
        // ...
    }).then(x => x.toString().length ? x.json() : {})
    .then(resp => {
        if (resp.error)
            throw new Error(resp.error.message);

        return resp;
    });
get_request("/posts/" + id + "/comments")
    .then(action(resp => {
        this.requestInProgress = false;
        this.post = new PostModel(resp.post);
    }))
    .catch(action(err => {
        this.requestInProgress = false;
        this.error = err.toString();
    }));

Your code is much cleaner because it's grouped into 2 different parts: The sunny and bright part where everything works perfectly, and the gloomy part where everything goes wrong.

Discussion (0)