0

I would like to create my own custom error, something like this:

function CustomError(message) {
   Error.captureStackTrace(this);
   this.message = message;
   this.name = "SomeCustomError";
}
CustomError.prototype = Object.create(Error.prototype);

How should I integrate custom errors in angular? I would simply be able to throw the same custom error anywhere I am in angular, no matter if in a service, controller, or similar. I certainly wouldn't want to 'dependency inject' the CustomError each time.

throw CustomError('some message');

Or, if I am thinking about, I also could simply:

throw {name : "CustomError", message : "some message"};

Any thoughts?

sl3dg3
  • 5,026
  • 12
  • 50
  • 74
  • If I understand correctly, you want to override the default exception handler? If so, look at the docs: https://docs.angularjs.org/api/ng/service/$exceptionHandler. It seems you can also add functionality while retaining the original exception handling functionality using decorators: http://stackoverflow.com/questions/13595469/how-to-override-exceptionhandler-implementation – Praval 'Shaun' Tirubeni Jun 04 '15 at 08:32
  • No, I already did this. I just want to define my own custom errors, and I don't know how to make it globally available in angular. – sl3dg3 Jun 04 '15 at 08:44
  • Hmmm, seems like there is an option of creating and then adding the service to the rootScope so you don't have to continuously inject it in: http://stackoverflow.com/questions/14571714/angular-js-make-service-globally-accessible-from-controllers-and-view. Though, not sure if it still meet your requirements? – Praval 'Shaun' Tirubeni Jun 04 '15 at 08:47
  • Well, I actually also could append it to `$window` somewhere during my angular's bootstrap function. Just a thought, maybe not bad... – sl3dg3 Jun 04 '15 at 09:49
  • Sounds interesting. Post what your final solution ends up being. – Praval 'Shaun' Tirubeni Jun 04 '15 at 10:01

1 Answers1

1

In my app.js - bootstrap file, I have now something like that:

angular.module('myApp')
    .run(['$window',
        function($window) {

            function CustomError(message) {
                Error.captureStackTrace(this);
                this.message = message;
                this.name = "SomeCustomError";
            }
            CustomError.prototype = Object.create(Error.prototype);

            $window.CustomError = CustomError;
            // From here on, I can throw it anywhere: 
            // throw new CustomError("D'oh!");
        }
    ]);
sl3dg3
  • 5,026
  • 12
  • 50
  • 74