Repository navigation
Description
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/casestyle 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
ErrorBoundaryhandle 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
crutchcorn commentedon Sep 28, 2023
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
SerkanSipahi commentedon Sep 28, 2023
@crutchcorn
I would suggest the following syntax which is not verbose/explicit like
@try/@catchbut would be more aligned with the new control-flow syntax from the angular team:So alongside to
@emptywe could introduce@catchas a final condition.Den-dp commentedon Sep 28, 2023
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
JeanMeche commentedon Sep 28, 2023
Isn't this basically what has been described with the error block of the deferred loading ?
crutchcorn commentedon Sep 28, 2023
@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/@catchis 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
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).The problem is that #43504 does not solve the same issues as this proposed feature. See, I tried using
ErrorHandlerto implement this functionality at first in myuserlandsolution, 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
ErrorHandlerservice would not solve the same problems as this proposal as a result.The only solution is to add some kind of manual
try/catchor to add it on every component instantiation (which would cause massive overhead).@JeanMeche
It's possible. I'm admittedly not sure when the
defererror state is intended to be fired. The problem with this is thatdeferwould 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 thandeferelgreco247 commentedon Sep 28, 2023
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?crutchcorn commentedon Sep 28, 2023
@elgreco247 while I like the idea of a structural directive more than what I had prior, a few thoughts:
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/catchcompiled directly into our template functions (from Angular's compiler)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
elgreco247 commentedon Sep 29, 2023
@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.
elgreco247 commentedon Sep 29, 2023
@crutchcorn Having an implicit variable called
$errorin thecatchblock would be more consistent with thedeferblock behavior.pkozlowski-opensource commentedon Oct 11, 2023
This is really a duplicate of #18509 - just proposing the new block syntax. Let's centralize the discussion in #18509.
Duplicate of #18509.
crutchcorn commentedon Oct 11, 2023
@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.
pkozlowski-opensource commentedon Oct 11, 2023
@crutchcorn I don't think that a particular syntax changes anything here - someone would have to design the exact behaviour of such error boundaries.
crutchcorn commentedon Oct 11, 2023
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?
angular-automatic-lock-bot commentedon Nov 11, 2023
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.