Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom error classes in Ember?

What is the right way to create custom error classes in Ember and where to put the error class definition files in Ember CLI?

All code samples that I have found are messing around with JavaScript object prototypes. Why can't I just call Ember.Error.extend like we do for normal Ember objects?

Proper place for custom error classes should be under app/errors/ directory, but it seems that Ember CLI is not resolving those files.

like image 795
jaaksarv Avatar asked Jan 08 '23 14:01

jaaksarv


1 Answers

Create custom file for example in app/errors/ directory, and call it custom-error.js.

Use following code as base to declare your custom error class:

import Ember from 'ember';

let CustomError = function (errors, message = 'This error is result of my custom logic.') {
  Ember.Error.call(this, message);

  this.errors = errors || [
    {
      title: 'This is custom error.',
      detail: message
    }
  ];
}

CustomError.prototype = Object.create(Ember.Error.prototype);

export default CustomError;

Then if you want to use this error somewhere:

import Ember from 'ember';
import CustomError from '../errors/custom-error';

export default Ember.Controller.extend({
  appName: 'Ember Twiddle',
  testCustomError: Ember.on('init', () => {
    let customErrorInstance = new CustomError();
    console.log(customErrorInstance);
  })
});

Result of console.log(customErrorInstance) is:

CustomError {description: undefined, fileName: undefined, lineNumber: undefined, message: "This error is result of my custom logic.", name: "Error"…}

  • Working demo.
  • Full code behind demo.
like image 164
Daniel Kmak Avatar answered Mar 11 '23 23:03

Daniel Kmak