Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept all errors in a class instance?

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.

like image 944
Fan Cheung Avatar asked Oct 19 '20 08:10

Fan Cheung


People also ask

What is an error interceptor and how does it work?

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.

How do I intercept a context in efef?

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.

How do you handle unhandled exceptions in a class?

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.

How to prevent 500 level HTTP error responses in apicontroller?

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.


Video Answer


1 Answers

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.

like image 145
Bergi Avatar answered Oct 09 '22 15:10

Bergi