I am trying to find a way to handle if an undefined error is thrown in my component template. When this occurs the app will break, the desired solution is to navigate to an "app error" component or replace the errored component with an "app error" component so that the app remains in a functioning state.
Asked
Active
Viewed 4,515 times
2 Answers
1
You can use try/catch blocks on your code but it can be tedious to manage in bigger applications. Instead, you can create your own error handling logic by extending the ErrorHandler from @angular/core.
Something like this;
import { ErrorHandler } from '@angular/core';
@Injectable()
export class YourErrorHandler implements ErrorHandler {
handleError(error) {
// your custom error handling logic
}
}
Then, add it to your root module like this;
@NgModule({
providers: [{provide: ErrorHandler, useClass: GlobalErrorHandler}]
})
-
Will this work for errors occurring in the component.html template file also? – Shane Jul 24 '19 at 11:16
-
No will it not! The only way is to write clean code! – JohnnyDevNull Jul 24 '19 at 11:43
-
Thank you for your response, I am looking for a way to catch issues in production that we may have missed, we already abide by all of these clean coding standards – Shane Jul 25 '19 at 12:02
0
There are no general way to catch all undefined
at one place.
This error just occurs when you write code that is not secure or/and not clean enough.
Some good practices area:
- initialize values
const myVar: string = null;
class MyClass {
public myAttr: string = null
}
- Set only value if not undefined or null or both
// matches not null & not undefined
if (newVal != null) {
myVar = newVal;
}
// matches only not undefined
if (newVal !== undefined) {
myVar = newVal;
}
// matches only not null
if (newVal !== null) {
myVar = newVal
}
- Check Object path's
Example see here: https://stackoverflow.com/a/2631198/3634274

JohnnyDevNull
- 951
- 1
- 8
- 20
-
1Thank you for your response, I am looking for a way to catch issues in production that we may have missed, we already abide by all of these clean coding standards – Shane Jul 25 '19 at 12:02
-
Some day's ago i've researched in a smiliar direction and maybe one of these topics could help you: https://stackoverflow.com/questions/19846078/how-to-read-from-chromes-console-in-javascript/19846113#19846113 https://stackoverflow.com/questions/11403107/capturing-javascript-console-log/11403146#11403146 – JohnnyDevNull Jul 26 '19 at 14:09