Currently, I have an angular application with a method decorator to handle errors of all the methods in the component. It catches all the errors from methods, But it is unable to catch the error inside subscribe. Any suggestions to do this?
This is my current code.
This is the sampling method I want to catch the errors
#logActionErrors()
getEmailSettings() {
this.sharedService.getSMTPConfigurations().subscribe(() => {
throw('this is an error');
}, (ex) =>{
console.log(ex);
})
}
This is my Method Decorator
export function logActionErrors(): any {
return function (target: Function, methodName: string, descriptor: any) {
const method = descriptor.value;
descriptor.value = function (...args: any[]) {
try {
let result = method.apply(this, args);
// Check if method is asynchronous
if (result && result instanceof Promise) {
// Return promise
return result.catch((error: any) => {
handleError(error, methodName, args, target.constructor.name);
});
}
if(result && result instanceof Observable ){
console.log(methodName);
result.pipe(catchError((error: any) => {
console.log(error);
handleError(error, methodName, args, this.constructor.name);
return result
}))
}
// Return actual result
return result;
} catch (error:any) {
handleError(error, methodName, args, target.constructor.name);
}
}
return descriptor;
}
}
I want to catch this throw('this is an error'); error on this sample. any suggestions to do this?
Related
How do developers structure their programs if they want to have a top-level error handling function?
The immediate thought that came into my mind was to wrap a try..catch to the main function, however, this does not trigger errors from callbacks?
try {
main();
} catch(error) {
alert(error)
}
function main() {
// This works
throw new Error('Error from main()');
document.querySelector('button').addEventListener('click', function() {
// This doesn throw
throw new Error ('Error from click callback');
})
}
<button>
Click me to see my callback error
</button>
Try-catch functionality around already existing functions/methods gets achieved best by wrapper approaches.
For the OP's use case one needs a modifying wrapper function which explicitly targets the handling of "after throwing" ...
// - try-catch wrapper which specifically
// targets the handling of "after throwing".
function afterThrowingModifier(proceed, handler, target) {
return function (...argsArray) {
let result;
try {
result = proceed.apply(target, argsArray);
} catch (exception) {
result = handler.call(target, exception, argsArray);
}
return result;
}
}
function failingClickHandler(/* event */) {
throw new Error('Error from click callback');
}
function afterTrowingHandler(error, [ event ]) {
const { message, stack } = error
const { type, currentTarget } = event;
console.log({
error: { message, stack },
event: { type, currentTarget },
});
}
function main() {
document
.querySelector('button')
.addEventListener('click', afterThrowingModifier(
failingClickHandler, afterTrowingHandler
));
}
main();
body { margin: 0; }
.as-console-wrapper { min-height: 85%!important; }
<button>
Click me to see my callback error
</button>
One of cause can implement prototype based abstractions for a function modifying failure handling like afterThrowing or afterFinally. Then the above main example code changes to something more expressive like ...
function afterTrowingHandler(error, [ event ]) {
const { message, stack } = error
const { type, currentTarget } = event;
console.log({
error: { message, stack },
event: { type, currentTarget },
});
}
function main() {
document
.querySelector('button')
.addEventListener('click', (function (/* event */) {
throw new Error('Error from click callback');
}).afterThrowing(afterTrowingHandler));
}
main();
body { margin: 0; }
.as-console-wrapper { min-height: 85%!important; }
<button>
Click me to see my callback error
</button>
<script>
(function (Function) {
function isFunction(value) {
return (
typeof value === 'function' &&
typeof value.call === 'function' &&
typeof value.apply === 'function'
);
}
function getSanitizedTarget(value) {
return value ?? null;
}
function afterThrowing/*Modifier*/(handler, target) {
target = getSanitizedTarget(target);
const proceed = this;
return (
isFunction(handler) &&
isFunction(proceed) &&
function afterThrowingType(...argumentArray) {
const context = getSanitizedTarget(this) ?? target;
let result;
try {
// try the invocation of the original function.
result = proceed.apply(context, argumentArray);
} catch (exception) {
result = handler.call(context, exception, argumentArray);
}
return result;
}
) || proceed;
}
// afterThrowing.toString = () => 'afterThrowing() { [native code] }';
Object.defineProperty(Function.prototype, 'afterThrowing', {
configurable: true,
writable: true,
value: afterThrowing/*Modifier*/
});
}(Function));
</script>
In javascript you can override global onerror, catching most of the errors:
window.onerror = function(message, source, lineno, colno, error) { ... };
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
In your case:
window.onerror = function(message, source, lineno, colno, error) {
console.error(message);
alert(message);
return false
};
function main() {
// This works
throw new Error('Error from main()');
document.querySelector('button').addEventListener('click', function() {
// This doesn throw
throw new Error ('Error from click callback');
})
}
main();
Some extra info:
https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror
Added after questions if Promise would raise the error, lets test:
window.onerror = (message, source, lineno,colno,error)=>{
console.error(`It does!, ${message}`);
};
const aFn = ()=>{
return new Promise((resolve)=>{
setTimeout(()=>{
throw new Error("whoops")
}, 3000);
});
}
aFn();
Result:
VM1163:2 It does!, Script error.
window.onerror # VM1163:2
error (asynchroon)
(anoniem) # VM1163:1
VM1163:7 Uncaught Error: whoops
at <anonymous>:7:19
I receive a complex object, let's say it will look like this:
complexObject: {
fruits: string[],
vegetables: string[],
milk: [] | [{
expirationDate: string,
quantity: string
}]
}
So, the logic is, that when I receive an empty object (milk will be just []), the verifyObject method will return undefined (the further logic is more complex and has to receive undefined...); the same case will be when the method will be called with an empty/undefined object.
The only verification, for the milk, should be like this:
If we have milk, then it needs to have both quantity and expirationDate, else it should return false.
The problem is, that when I send an object like this:
{
'fruits': ['apples', 'bananas'],
'vegetables': ['tomatoes'],
'milk': [{
'quantity': '10'
}]
}
in the checkAndAssign method it will see, the error, print the console.log, but it won't stop there and it will add the object to the result.
Also, in the verifyObject method, it will enter catch block, but upper it won't throw the error and it will resolve the promise instead, returning the result...
I want to stop the execution when I receive a wrong message and propagate the error...
This is the code:
verifyObject(complexObject) {
return new Promise((resolve, reject) => {
const result = {};
const propertiesEnum = ['fruits', 'vegetables', 'milk'];
if (!complexObject) {
resolve({ result: undefined });
} else {
this.checkAndAssign(complexObject, result)
.catch((err) => {
console.log('enter error');
reject({ message: err });
})
if (!Object.keys(result).length) {
console.log('resolve with undefined');
resolve({ result: undefined });
}
console.log('resolve good');
resolve({ result });
}
})
}
private checkAndAssign(complexObject, result) {
return new Promise((resolve, reject) => {
for (const property of complexObject) {
if(complexObject[property] && Object.keys(complexObject[property]).length)
if(property === 'milk' && this.verifyMilk(complexObject[property]) === false) {
console.log('rejected');
reject('incomplete');
}
Object.assign(result, {[property]: complexObject[property]})
console.log('result is...:>', result);
}
console.log('final result:>', result);
resolve(result);
});
}
private verifyMilk(milk:any): boolean {
for(const item of milk) {
if(!(item['expirationDate'] && item['quantity'])) {
return false;
}
}
return true;
}
Calling reject doesn't terminate the function you call it from. reject is just a normal function call. Once the call is complete, the function calling it continues.
If you don't want that, use return:
private checkPropertyAndAssignValue(complexObject, result) {
return new Promise((resolve, reject) => {
for (const property of complexObject) {
if(complexObject[property] && Object.keys(complexObject[property]).length)
if(property === 'milk' && this.verifyMilk(complexObject[property]) === false) {
console.log('rejected');
reject('incomplete');
return; // <================================================ here
}
Object.assign(result, {[property]: complexObject[property]})
console.log('result is...:>', result);
}
console.log('final result:>', result);
resolve(result);
});
}
Then verifyObject needs to wait for the fulfillment of the promise from checkPropertyAndAssignValue. verifyObject's code falls prey to the explicit promise creation anti-pattern: It shoudln't use new Promise, because it already has a promise from checkPropertyAndAssignValue. Avoiding the anti-pattern also helps avoid this error:
verifyObject(complexObject) {
const result = {};
const propertiesEnum = ['fruits', 'vegetables', 'milk'];
if (!complexObject) {
return Promise.resolve({ result: undefined });
}
return this.checkPropertyAndAssignValue(complexObject, result)
.then(() => {
if (!Object.keys(result).length) {
console.log('resolve with undefined');
return { result: undefined };
}
console.log('resolve good');
return { result };
})
.catch((err) => {
console.log('enter error');
throw { message: err }; // *** Will get caught by the promise mechanism and turned into rejection
});
}
As an alternative: If you're writing this code for modern environments, you may find async functions and await to be more familiar, since they use the same constructs (throw, try, catch) that you're used to from synchronous code. For example:
async verifyObject(complexObject) {
const result = {};
const propertiesEnum = ['fruits', 'vegetables', 'milk'];
if (!complexObject) {
return { result: undefined };
}
try {
await this.checkPropertyAndAssignValue(complexObject, result);
// ^^^^^−−−−− waits for the promise to settle
if (!Object.keys(result).length) {
console.log('return undefined');
return { result: undefined };
}
console.log('return good');
return { result };
} catch (err) {
console.log('enter error');
throw { message: err }; // *** FWIW, suggest making all rejections Error instances
// (even when using promises directly)
}
}
private async checkPropertyAndAssignValue(complexObject, result) {
// *** Note: This used to return a promise but didn't seem to have any asynchronous
// code in it. I've made it an `async` function, so if it's using something
// that returns a promise that you haven't shown, include `await` when getting
// its result.
for (const property of complexObject) {
if(complexObject[property] && Object.keys(complexObject[property]).length)
if(property === 'milk' && this.verifyMilk(complexObject[property]) === false) {
throw 'incomplete'; // *** FWIW, suggest making all rejections Error instances
// (even when using promises directly)
}
Object.assign(result, {[property]: complexObject[property]})
console.log('result is...:>', result);
}
console.log('final result:>', result);
return result;
}
Say I have a class like this
class SomeUIComponentDataStore {
async function getUser() {
try { //do something that can fail}
catch(e) {
// gracefully fail, setting portion of ui to fail state
Sentry.captureException(e); // report to some metrics service
}
}
}
I repeat that pattern for every async function. Where on failure I respond to the error, and then report it to some service (in this case that service is Sentry).
Is there anyway I can create a BaseClass, that will automatically decorate my catch statement with Sentry.caputreException(). Or do i have to manually write it each time a I see an error.
You could define a decorator to reuse that logic and decorate methods that can throw:
function catchError(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = function(...args) {
try {
return original.apply(this, args);
} catch (e) {
Sentry.captureException(e); // report to some metrics service
}
}
}
}
function catchErrorAsync(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = async function(...args) {
try {
return await original.apply(this, args);
} catch (e) {
Sentry.captureException(e); // report to some metrics service
}
}
}
}
class SomeUIComponentDataStore {
#catchErrorAsync
async getUser() {
//do something that can fail
}
#catchError
otherMethod() {
//do something that can fail
}
}
You could create a base class with the Sentry.captureException(e);, and then have overrideable functions for the custom try/catch functionality.
class BaseClass {
function onGetUser() {
throw new Error("Method not implemented");
}
function onGetUserFail() {
throw new Error("Method not implemented");
}
async function getUser() {
try {
onGetUser();
} catch (e) {
onGetUserFail();
Sentry.captureException(e);
}
}
}
class SomeUIComponentDataStore extends BaseClass {
function onGetUser() {
// do something
}
function onGetUserFail() {
// do something
}
}
I am trying out decorators, I have written a decorator that basically returns a new function that does some `console.log.
This is what my decorator looks like:
function test(target, name, descriptor) {
const original = descriptor.value;
console.log("bbau");
if (typeof original === 'function') {
descriptor.value = function (...args) {
console.log(`Arguments: ${args}`);
try {
console.log("executing");
const result = original.apply(this, args);
console.log("done");
console.log(`Result: ${result}`);
return result;
} catch (e) {
console.log(`Error: ${e}`);
throw e;
}
}
}
return descriptor;
}
And this is how I am using it:
class TestController extends BaseController<//..> {
// ...
#test
testIt(req: Request, res: Response) : Response {
this.sendResponse();
}
sendResponse(options: ISendResponseOptions, res: Response) : Response {
// return response
}
}
``
However, when executed an error is raised: Error: TypeError: Cannot read property 'sendResponse' of undefined.
Any thoughts about what it could be? Thanks!
You should generally use an arrow function when you want to capture this from the context you declared the function in (or when this does not matter). In this case you really want this to be the object the function was called on so you should use a regular function :
const test = (target, name, descriptor) => {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = function (...args) {
console.log(`Arguments: ${args}`);
try {
console.log("executing");
const result = original.apply(this, args);
console.log("done");
console.log(`Result: ${result}`);
return result;
} catch (e) {
console.log(`Error: ${e}`);
throw e;
}
}
}
return descriptor;
}
You can test it out in the playground
If you use this function as a parameter to another function you should also call bind to set this for the function (otherwise the caller will determine the value of this):
router.route("/").post(testController.testIt.bind(testController))
I'm using the babel 7 decorator plugin and I have a simple class and I want to decorate each method in a simple try catch wrapper.
This is what've done:
const errorHandler = () => {
return (target, property, descriptor) => {
try {
return descriptor
} catch (e) {
console.error('error from the decorator', e)
}
}
}
In this is a sample of my class:
class Example {
#errorHandler
addComponent() {
throw new Error('Error')
}
}
But when I'm executing the function it's not going throw the decorator before execution, only pre-evaluating when the class is being initialized.
any ideas?
You are returning descriptor, which is a function object and it gets executed by caller outside your try/catch block. To intercept exception - you should execute descriptor yourself.
The correct code is:
const errorHandler = (target, property, descriptor) => {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = async function(...args) {
try {
return await original.apply(this, args);
} catch (e) {
console.error('error from the decorator', e)
}
}
}
}
class Example {
#errorHandler
addComponent() {
throw new Error('Error')
}
}
new Example().addComponent();