Posts

Showing posts with the label Try Catch

Can You Catch All Errors Of A React.js App With A Try/catch Block?

Answer : React 16 introduced Error Boundaries and the componentDidCatch lifecycle method: class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } Then you can use it as a regular component: <ErrorBoundary> <MyWidget /> </ErrorBoundary> Or you can wrap your root component with the npm package react-error-boundary, and set a fallback component and behavior. import {ErrorBoundary} from 'react-error-boundary'; const myErrorHandler = (error: Error, componentStack: string) => { //...

Catching Stripe Errors With Try/Catch PHP Method

Answer : If you're using the Stripe PHP libraries and they have been namespaced (such as when they're installed via Composer) you can catch all Stripe exceptions with: <?php try { // Use a Stripe PHP library method that may throw an exception.... \Stripe\Customer::create($args); } catch (\Stripe\Error\Base $e) { // Code to do something with the $e exception object when an error occurs echo($e->getMessage()); } catch (Exception $e) { // Catch any other non-Stripe exceptions } I think there is more than these exceptions ( Stripe_InvalidRequestError and Stripe_Error ) to catch. The code below is from Stripe's web site. Probably, these additional exceptions, which you didn't consider, occurs and your code fails sometimes . try { // Use Stripe's bindings... } catch(Stripe_CardError $e) { // Since it's a decline, Stripe_CardError will be caught $body = $e->getJsonBody(); $err = $body['error']; print('Status is:...

Catch Vs Catch (Exception E) And Throw Vs Throw E

Answer : I think there are two questions here. What is the difference between throw and throw e; ? I don't think there is ever a good reason to write catch (Exception e) { throw e; } . This loses the original stacktrace. When you use throw; the original stacktrace is preserved. This is good because it means that the cause of the error is easier to find. What is the difference between catch and catch (Exception e) ? Both of your examples are the same and equally useless - they just catch an exception and then rethrow it. One minor difference is that the first example will generate a compiler warning. The variable 'e' is declared but never used It makes more sense to ask this question if you had some other code in your catch block that actually does something useful. For example you might want to log the exception: try { int value = 1 / int.Parse("0"); } catch (Exception e) { LogException(e); throw; } Now it's necessary ...