ErrorHandler.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. sap.ui.define([
  2. "sap/ui/base/Object",
  3. "sap/m/MessageBox"
  4. ], function (UI5Object, MessageBox) {
  5. "use strict";
  6. return UI5Object.extend("sap.ui.demo.orderbrowser.controller.ErrorHandler", {
  7. /**
  8. * Handles application errors by automatically attaching to the model events and displaying errors when needed.
  9. * @class
  10. * @param {sap.ui.core.UIComponent} oComponent reference to the app's component
  11. * @public
  12. * @alias sap.ui.demo.orderbrowser.controller.ErrorHandler
  13. */
  14. constructor : function (oComponent) {
  15. this._oComponent = oComponent;
  16. this._oModel = oComponent.getModel();
  17. this._bMessageOpen = false;
  18. this._oModel.attachMetadataFailed(function (oEvent) {
  19. var oParams = oEvent.getParameters();
  20. this._showServiceError(oParams.response);
  21. }, this);
  22. this._oModel.attachRequestFailed(function (oEvent) {
  23. var oParams = oEvent.getParameters();
  24. // An entity that was not found in the service is also throwing a 404 error in oData.
  25. // We already cover this case with a notFound target so we skip it here.
  26. // A request that cannot be sent to the server is a technical error that we have to handle though
  27. if (oParams.response.statusCode !== "404" || (oParams.response.statusCode === 404 && oParams.response.responseText.indexOf("Cannot POST") === 0)) {
  28. this._showServiceError(oParams.response);
  29. }
  30. }, this);
  31. },
  32. /**
  33. * Shows a {@link sap.m.MessageBox} when a service call has failed.
  34. * Only the first error message will be display.
  35. * @param {string} sDetails a technical error to be displayed on request
  36. * @private
  37. */
  38. _showServiceError : async function (sDetails) {
  39. if (this._bMessageOpen) {
  40. return;
  41. }
  42. this._bMessageOpen = true;
  43. const oResourceBundle = await this._oComponent.getModel("i18n").getResourceBundle();
  44. MessageBox.error(
  45. oResourceBundle.getText("errorText"),
  46. {
  47. id : "serviceErrorMessageBox",
  48. details : sDetails,
  49. styleClass : this._oComponent.getContentDensityClass(),
  50. actions : [MessageBox.Action.CLOSE],
  51. onClose : function () {
  52. this._bMessageOpen = false;
  53. }.bind(this)
  54. }
  55. );
  56. }
  57. });
  58. });