Let's say if I have a class
class Foo {
doSomething() { throw 'error'; }
doOtherthing() { throw 'error2'; }
handleError(e) {}
}
Is there any implementation to automatically intercept/catch any error that happens in this class and redirect it to an error handling method, in this case handleError()
e.g
const foo = new Foo()
foo.doSomething()
That should trigger errorHandler(). Angular has such implementation and I am not sure how it got done.
First things first, let’s understand the error interceptor. What is the Error Interceptor? An error interceptor is a special type of interceptor which is used for handling errors that arise while making an HTTP request.
EF 6 provides the ability to intercept the context by implementing the IDbCommandInterceptor interface. The IDbCommandInterceptor interface includes methods which intercept an instance of DbContext and allow you to execute your custom logic before or after a context executes commands or queries.
An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions. You must also register your filter as part of the Startup code.
For ASP.NET web applications, you can’t prevent users from receiving 500 level HTTP internal server error responses when an exception is thrown in an ApiController. How you can handle this depends whether you are using various ASP.NET frameworks or ASP.NET Core.
You can wrap every method inside an error-handling wrapper systematically:
for (const name of Object.getOwnPropertyNames(Foo.prototype))
const method = Foo.prototype[name];
if (typeof method != 'function') continue;
if (name == 'handleError') continue;
Foo.prototype.name = function(...args) {
try {
return method.apply(this, args);
} catch(err) {
return this.handleError(err, name, args);
}
};
}
Notice this means that handleError
should either re-throw the exception or be able to return a result for all methods of the class (which can be undefined
of course).
For asynchronous methods, you'd check whether the return value is a promise and then attach an error handler with .catch()
before returning it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With