Reputation: 10830
I have an Angular application using Sentry.io for logging. I created a custom error handler class where I initialise Sentry and I would like to avoid log server errors (404 Not Found or 500 Server Error).
I read that if a Network call fails in Angular, the exception is bubbled up and not catched in the ErrorHandler (hence it would not trigger handleError
method).
However even if I use the beforeSend()
method, as suggested to face this very specific case, the console logs are written (eg. SENTRY SKIPPING EVENT), but all the server errors keep being logged in Sentry.
export class MyhErrorHandler implements ErrorHandler {
if (environment.production) {
Sentry.init({
dsn: 'https://[email protected]/123456789',
environment: this.environmentData.env,
beforeSend(event) {
try {
if (this.isServerError(JSON.stringify(event))) {
console.log('------ SENTRY SKIPPING EVENT: ', {event});
return null;
}
} catch (e) {
console.log('------ SENTRY ERROR: ', {e});
}
return event;
}
});
}
handleError(err: any): void {
if (!this.isServerError(err)) {
const errorText = MyhErrorHandler.getError(err);
Sentry.captureException(errorText);
}
}
private isServerError(error: any): boolean {
if (!error) {
return false;
}
const regex = new RegExp(
`500 Internal Server Error|401 Unauthorized|403 Forbidden|404 Not Found|502 Bad Gateway|503 Service Unavailable`,
'mi'
);
return regex.test(JSON.stringify(error);
} catch (error) {
Sentry.captureException(`Error in myh-error-handler while parsing error Obj: ${errorText} -- ${error.message}`);
}
}
}
Upvotes: 4
Views: 3617
Reputation: 10830
I found a solution to my problem and I write it here so it might help others.
I used the property ignoreErrors
accepting a string or a RegEx during the Sentry the initialisation:
const serverErrorsRegex = new RegExp(
`500 Internal Server Error|401 Unauthorized|403 Forbidden|404 Not Found|502 Bad Gateway|503 Service Unavailable`,
'mi'
);
Sentry.init({
dsn: 'https://[email protected]/12345678',
environment: this.environmentData.env,
// We ignore Server Errors. We have to define here since Angular
// http client uses setTimeout to detect http call progress.
// And when the call fails, it throws an exception inside that timeout
// that bubbles up higher to the main Angular's error handler.
ignoreErrors: [serverErrorsRegex]
});
In the Regex I used the flags mi
standing for:
More details about Regex flags here.
Upvotes: 8