Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle exceptions?

Angular has a great $exceptionHandler. Is there anything like this for react.js?

I would like to log my errors to an external API. Examples:

  • https://github.com/occ/TraceKit
  • http://trackjs.com/
  • https://plus.google.com/+PaulIrish/posts/12BVL5exFJn
like image 646
Eric Avatar asked Mar 26 '15 00:03

Eric


People also ask

How do you handle exceptions in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

How do you handle exceptions in C++?

Handling Exceptions in C++ Exception handling in C++ is done using the try and catch keywords. To catch exceptions, a portion of code is placed under inspection. This is done by enclosing this portion of code in a try block. When an exception occurs within the try block, control is transferred to the exception handler.


1 Answers

There's no magic like in angular. If there's an uncaught error, it propagates up the scopes until it hits window, and then an error event is emitted – the same behavior as an error without react.

var App = React.createClass({
  render: function(){
    throw new Error("rawr!");
    return <div>Hello, world!</div>
  }
});

window.addEventListener('error', function(e){
  // e instanceof ErrorEvent
  console.error('caught the error: ' + e.message);
});

chrome console displaying the error

If you look into cross browser support, please update this answer or add a comment with citations.

Instead of logging it to the console (which already happens by default), you can send it anywhere you like.

Unlike some other frameworks, an uncaught error is always a bug in your code. It should never happen.

You may also need to do some special handling of promise errors by explicitly adding a .catch(reportError) to the end of chains, and checking that it's a TypeError or ReferenceError.

like image 190
Brigand Avatar answered Sep 19 '22 07:09

Brigand