Reputation: 1490
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.
Upvotes: 4
Views: 1212
Reputation: 18682
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"…}
Upvotes: 9