Skip to content

@try/@catch Control Flow  #51941

Closed as not planned
Closed as not planned

Description

@crutchcorn

Which @angular/* package(s) are relevant/related to the feature request?

common, compiler-cli, compiler, core

Description

tl;dr: I am proposing a new @try/@catch control flow to catch errors that occur in Angular component's constructor method.

@try {
	<error-throwing-component/>
} @catch (e: any) {
	<handle-error [error]="e"/>
}

A longer-form blog post explaining this problem and the solution can be found here: https://unicorn-utterances.com/posts/angular-constructor-error-behavior

The problem

When rendering the following:

import 'zone.js/dist/zone';
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';

@Component({
  selector: 'throw-an-error',
  standalone: true,
  template: `<p>🙈</p>`,
})
class ErrorComponent {
  constructor() {
    throw 'This is an error';
  }
}

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [ErrorComponent],
  template: `
    <p>Before</p>
    <!-- Try hiding and showing this line -->
    <throw-an-error/>
    <!-- This never shows up -->
    <p>After</p>
  `,
})
class AppComponent {}

bootstrapApplication(AppComponent);

The <p>Before</p> renders, but the <throw-an-error/> does not. Confusingly (to many), the <p>After</p> does not render either. This is because Angular's template compiler doesn't wrap component instances in a try/catch, which leads to the error propagating upward and breaking any UI rendering past the thrown constructor error.

Proposed solution

The proposed solution

To solve for this issue, I'd like to propose (and offer to implement) the following syntax:

@try {
	<error-throwing-component/>
} @catch (e: any) {
	<handle-error [error]="e"/>
}

Which would allow us to catch any constructor errors while allowing the rest of the components to be rendered as-expected. I would reasonably expect this to be compiled to some pseudo-code akin to:

let attemptedRender = null;
try {
	attemtedRender = renderComponent(ErrorThrowingComponent)
} catch (e) {
	cleanup(attemptedRender)
	render(HandleErrorComponent, {inputs: {error: e}})
}

Alternatives considered

Userland solutions

While <component/> wouldn't be able to recover from the error in runtime, it's possible to wrap this component in a try/catch block by moving it to a ViewContainerRef createComponent call:

@Component({
  selector: 'error-catcher',
  standalone: true,
  imports: [NgIf],
  template: `
  <div *ngIf="error">
    <h1>There was an error</h1>
  </div>
  <ng-template #compTemp></ng-template>
  `,
})
class ErrorCatcher implements OnInit {
  @ViewChild('compTemp') compTemp!: TemplateRef<any>;
  @Input({ required: true }) comp!: any;

  containerRef = inject(ViewContainerRef);

  error: any = null;

  ngOnInit() {
    try {
      this.containerRef.createComponent(this.comp);
    } catch (e) {
      this.error = e;
    }
  }
}

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [ErrorCatcher],
  template: `
    <p>Before</p>
    <error-catcher [comp]="comp"/>
    <p>After</p>
  `,
})
class AppComponent {
  comp = ErrorComponent;
}

We can even expand this functionality to accept inputs and handle outputs mostly as expected:

Demo StackBlitz showing a user-land fix to the error boundary problem

Alternative demo using a structural directive instead

However, this comes with substancial issues:

  • The syntax and tooling are not consistent with other Angular components
  • Outputs and inputs are very loose typings now, which may lead to more bugs, not less
  • Outputs are not bound in the same way, requiring weird switch/case style coding and manually typing

Prior art

This idea was directly inspired by React's ErrorBoundary system, which similarly handles errors thrown during the render function.

Note that neither this proposal, nor React's ErrorBoundary handle errors that occur in event handlers, only the runtime.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Example "componentStack":
    //   in ComponentThatThrows (created by App)
    //   in ErrorBoundary (created by App)
    //   in div (created by App)
    //   in App
    logErrorToMyService(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.fallback;
    }

    return this.props.children;
  }
}

// ...

<ErrorBoundary fallback={<p>Something went wrong</p>}>
  <Profile />
</ErrorBoundary>

Activity

  1. crutchcorn commented on Sep 28, 2023

    @crutchcorn
    ContributorAuthor

    While this feature request is closely related to:

    #18509
    #43504

    I believe the solution approach is unique enough to warrant it's own discussion and investigation

  2. SerkanSipahi commented on Sep 28, 2023

    @SerkanSipahi

    @crutchcorn

    I would suggest the following syntax which is not verbose/explicit like @try / @catch but would be more aligned with the new control-flow syntax from the angular team:

    @if (cond) {
    	<error-throwing-component-1/>
    } @else {
    	<error-throwing-component-2/>
    } @catch (e: any) {
    	<handle-error [error]="e"/>
    }
    

    So alongside to @empty we could introduce @catch as a final condition.

  3. Den-dp commented on Sep 28, 2023

    @Den-dp
    Contributor

    Thanks for sharing this idea!

    While definitely bringing the value, I see that such control flow keywords will also bring a mental overhead where users may start reasoning upfront on whether the component they see in a template throws an error or not (or even worse - wrap it every time).

    My vote goes to #43504 cause I don't want to embrace the defensive programming in templates, complicating them

  4. JeanMeche commented on Sep 28, 2023

    @JeanMeche
    Member

    Isn't this basically what has been described with the error block of the deferred loading ?

  5. crutchcorn commented on Sep 28, 2023

    @crutchcorn
    ContributorAuthor

    @SerkanSipahi the challenge with your method is that it seems to require an @if, which isn't quite the goal of this feature request. After all, you're likely to want to wrap a component in this clause without a conditional. These concepts are fairly distinct from one another and, IMO should be treated as such.

    Further, as I'm concerned, the explicitness of @try/@catch is a benefit, not a detriment. I'd rather make immediately clear what's occurring under-the-hood than attempt to rename/abstract and cause confusion.

    @Den-dp

    users may start reasoning upfront

    Isn't this true for all new features, not just this proposal? In my mind, there's a gap today between the Angular and React (and friends) ecosystem. It's a feature that I've actively seen prevent larger-scale downtimes in production applications in the past. While I understand this concern broadly, I think the benefits largely outweigh the downsides. Further, this can be remedied with general outlines in the docs of when to @try/@catch (landmarks, mission critical aspects of the app, etc).

    My vote goes to #43504 cause I don't want to embrace the defensive programming in templates, complicating them

    The problem is that #43504 does not solve the same issues as this proposed feature. See, I tried using ErrorHandler to implement this functionality at first in my userland solution, even:

    https://stackblitz.com/edit/stackblitz-starters-srvxcz?file=src%2Fmain.ts

    However, because of the outlined cause of the problem, the error never triggers a UI update. Localizing the ErrorHandler service would not solve the same problems as this proposal as a result.

    The only solution is to add some kind of manual try/catch or to add it on every component instantiation (which would cause massive overhead).

    @JeanMeche

    Isn't this basically what has been described with the #50716 ?

    It's possible. I'm admittedly not sure when the defer error state is intended to be fired. The problem with this is that defer would add in lazy initialization, wouldn't it? This alone may make it a non-starter for some parts of the app (like a header bar) that would want to be eagerly loaded but defensively guarded. Especially for high-importance parts of the app, I think something like this feature request makes more sense than defer

  6. elgreco247 commented on Sep 28, 2023

    @elgreco247

    Couldn't you solve this in userland with a structural directive (e.g. <error-throwing-component *onError="errorTemplateVar"/>)? What is the added benefit of having this syntax built into the compiler?

  7. crutchcorn commented on Sep 28, 2023

    @crutchcorn
    ContributorAuthor

    @elgreco247 while I like the idea of a structural directive more than what I had prior, a few thoughts:

    1. Adding in a template ref feels like it would be slower simply due to the overhead of having to construct a template rather than add a try/catch compiled directly into our template functions (from Angular's compiler)

    2. Even if there is a userland solution that's more elegant than a clunky component, I'd still rather like to see this functionality supported first-class in the framework. There's a training problem inherent to this issue: Right now as there's no official solution to this problem, I'd venture a guess that most Angular devs are not aware of this problem. In fact, while I've been working with Angular right after the 2.0 launch, I thought this behavior was handled by the framework itself until I stumbled upon this behavior by chance while writing a book on the topic.

    That said, if that structural directive would be helpful for anyone I'd added it to the OP and will link it here:

    https://stackblitz.com/edit/angular-error-boundary-userland-poc-warktp?file=src%2Fmain.ts,src%2Fon-error.directive.ts

  8. elgreco247 commented on Sep 29, 2023

    @elgreco247

    Isn't this basically what has been described with the error block of the deferred loading ?

    @JeanMeche I think the error block is only activated if the dynamic import of any of the defer block dependencies (components, directives, pipes) is unsuccessful. The instantiation of the dynamically imported components is not guarded.

  9. elgreco247 commented on Sep 29, 2023

    @elgreco247

    @crutchcorn Having an implicit variable called $error in the catch block would be more consistent with the defer block behavior.

    @try {
    	<error-throwing-component/>
    } @catch {
    	<handle-error [error]="$error.message"/>
    }
    
  10. added
    area: core
    core: control flow
    on Oct 2, 2023
  11. added this to the needsTriage milestone on Oct 2, 2023
  12. pkozlowski-opensource commented on Oct 11, 2023

    @pkozlowski-opensource
    Member

    This is really a duplicate of #18509 - just proposing the new block syntax. Let's centralize the discussion in #18509.

    Duplicate of #18509.

  13. added and removed
    core: control flow
    on Oct 11, 2023
  14. crutchcorn commented on Oct 11, 2023

    @crutchcorn
    ContributorAuthor

    @pkozlowski-opensource should I copy the top post/comment of this issue into #18509? What's the best way to re-request attention to this issue with the new syntax? As mentioned before, I'm more than happy to add a PR that solves this issue if the details are ironed out.

  15. pkozlowski-opensource commented on Oct 11, 2023

    @pkozlowski-opensource
    Member

    @crutchcorn I don't think that a particular syntax changes anything here - someone would have to design the exact behaviour of such error boundaries.

  16. crutchcorn commented on Oct 11, 2023

    @crutchcorn
    ContributorAuthor

    I'm not clear what you mean by "design the exact behavior of such error boundaries". Isn't that what this syntax fixes here? What's missing to help this idea move forward?

  17. angular-automatic-lock-bot commented on Nov 11, 2023

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  18. locked and limited conversation to collaborators on Nov 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corecore: error handling

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions