How to return an HTTP error in a response component?

On the server side, how should the reactjs component notify the node application of the return of an http error?

My first idea is to throw an error:

var notFound = function () {
    var error = new Error("Not Found");
    error.httpError = 404;
    throw error;    
};

var App = React.createClass({
    render: function () {
        return react.DOM.div(null,
            Locations({path: this.props.path},
                Location({path: "/", handler: home}),
                NotFound({handler: notFound})
            )
        );
    }
});

try {
    res.send(React.renderComponentToString(app()));
}
catch (err) {
    if(err.httpError) {
        res.send(err.httpError);
    } else {
        throw err;
    }
}

Is this a valid solution? Do you have another idea?

EDIT: I would like to extend this case to redirect HTTP 3xx, which are not errors. Does it change anything?

+4
source share
1 answer

I do not think this is related to React, but in fact in any environment.

I think this document will help you answer your own question: https://www.joyent.com/developers/node/design/errors

However, you should check out these (insufficiently) well-known rules from the Java world:

React , http, http. React HTML, catch. , .

, , , , , (.. w have have httpError). , , . , res.send(undefined);, , , , , , - .

, , . , . - :

if ( ValidPaths.contains(path) ) {
   render()
} else {
   res.send(404)
}

, , , - stacktrace. DOS, . . , DOS, :)

, , Javascript - : (

+1

Source: https://habr.com/ru/post/1548425/


All Articles