Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an http error in a react component?

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

My first idea was 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 it a valid solution? Do you have another idea in mind?

EDIT: I would like to extend this case to 3xx http redirection which are not errors. Does it change something?

like image 418
Julien Christin Avatar asked Jul 15 '14 02:07

Julien Christin


People also ask

How do you find the error in React?

React provides two lifecycle methods that a component can implement to determine if a rendering error has occurred in its child tree and respond accordingly. These two methods are componentDidCatch() and static getDerivedStateFromError() .

How do you handle HTTP error response in React?

Error handling with Error Boundaries — For class components. Error boundaries are the most straightforward and effective way to handle errors that occur within your React components. You can create an error boundary component by including the life cycle method componentDidCatch(error, info) if you use class component.

How do you throw an error in Reactjs?

import { useState } from "react"; const App = () => { const [error, setError] = useState(Error()); const throwError = () => { throw Error("I'm an error"); }; const crash = () => { try { throwError(); } catch (e) { setError(e); console.

Which React component will throw an error?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.


1 Answers

I don't think this is related to React but actually to any framework.

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

However, you should check these (not enough) well known rules from the Java world:

  • Java Style: Properly handling exceptions
  • http://jtechies.blogspot.fr/2012/07/item-61-throw-exceptions-appropriate-to.html

You are throwing in your React app exceptions that do not belong to the http abstraction, and thus should not be aware of the http status codes. You should rather throw meaningful exceptions for the abstraction of rendering a React app in inline HTML, and then catch these exceptions and choose the appropriate error code in the catch block. This is just a detail for your implementation but on large code bases it matters.

By the way, you should not assume that exceptions you can catch are always exceptions you throw (ie wìll have the httpError property). Any code can throw an exception, even if you are pretty sure that it won't it's not a bad idea to handle this. If this happens, you may end up with a result being res.send(undefined); which will perhaps trigger another exception, and you won't have the cause of that exception because it was swallowed by your assumption that your code doesn't throw any unexpected exception.

Another principle to know is to fail fast. If you can handle the error before rendering, you would rather handle it before. Something like:

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

If you have the possibility to handle the error without throwing an exception, just be aware that there is a cost to use exceptions, especially because of the stacktrace. There already have been DOS attacks on servers to generate a lot of exceptions on them. It is always better to not use exceptions for non exceptionnal things. Just be aware of it and choose yourself if a hacker trying to DOS you is exceptional or not :)

Anyway I think Javascript exception handling is a real pain :(

like image 165
Sebastien Lorber Avatar answered Oct 13 '22 10:10

Sebastien Lorber