Skip to content

Commit

Permalink
feat(decorators): add error handling for common model usage
Browse files Browse the repository at this point in the history
  • Loading branch information
velrest committed Oct 14, 2020
1 parent f0e446c commit 38155db
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
43 changes: 43 additions & 0 deletions addon/decorators/handle-model-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { assert } from "@ember/debug";

export default function (...args) {
const [{ routeFor404, errorMessage = "emeis.not-found" } = {}] = args;

const decorate = function (target, name, descriptor) {
const originalDescriptor = descriptor.value;

descriptor.value = function (...args) {
assert(
"Inject the `notification` as well as the `intl` service into your route to properly display errors.",
this.notification && this.intl
);

const catchErrors = (exception) => {
if (
routeFor404 &&
exception.isAdapterError &&
exception.errors[0].status === "404"
) {
this.notification.danger(this.intl.t(errorMessage));
this.replaceWith(routeFor404);
} else {
this.notification.danger(this.intl.t("emeis.general-error"));
}
};

try {
const result = originalDescriptor.apply(this, args);
return result.then ? result.catch(catchErrors) : result;
} catch (exception) {
catchErrors(exception);
}
};
};

// We can assume that the decorator was called without options
if (args.length === 3 && !args[0].routeFor404 && !args[0].errorMessage) {
return decorate(...args);
}

return decorate;
}
1 change: 1 addition & 0 deletions app/decorators/handle-model-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "ember-emeis/decorators/handle-model-errors";

0 comments on commit 38155db

Please sign in to comment.