0

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.

Shane
  • 659
  • 1
  • 9
  • 19

2 Answers2

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}]
})
ahmeticat
  • 1,899
  • 1
  • 13
  • 28
bahadrdsr
  • 424
  • 3
  • 7
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:

  1. initialize values
const myVar: string = null;

class MyClass {
  public myAttr: string = null
}
  1. 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
}
  1. Check Object path's

Example see here: https://stackoverflow.com/a/2631198/3634274

JohnnyDevNull
  • 951
  • 1
  • 8
  • 20
  • 1
    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
  • 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