sulu / SuluHeadlessBundle

Bundle that provides controllers and services for using Sulu as headless content management system
MIT License
45 stars 25 forks source link

support for error views #136

Closed DanielRuf closed 9 months ago

DanielRuf commented 10 months ago

In our setup we also render the React part of the headless bundle when a page is not found (404).

For that we had to patch the bundle to add support for views of the type "error" (and templates like 404).

After this we just needed some viewRegistry.add('error', '404', HeadlessErrorPage); in assets/headless/src/index.ts.

--- Resources/js-website/src/stores/viewDataStore.js    2023-10-17 17:43:35.981321988 +0200
+++ Resources/js-website/src/stores/viewDataStore.js    2023-10-17 17:45:21.141788587 +0200
@@ -14,6 +14,7 @@
                 this.setData(data);
             }).catch((error) => {
                 loglevel.warn('Error while loading view data for pathname "' + pathname + '".', error);
+                this.setData({type: 'error', template: JSON.stringify(error.status)});
                 this.loading = false;

                 throw error;
alexander-schranz commented 10 months ago

In our cases we currently returning that correclty in the error response. The headless bundle does not yet do that you need in your project in the error.html.twig or error.json.twig :

PHP / Twig Part (https://github.com/sulu/sulu/blob/2.5/src/Sulu/Bundle/WebsiteBundle/Controller/ErrorController.php#L72):

{{ {type: 'error', template: 'error', error: {
    status: status_code,
    statusText: status_text,
}}|json_encode }}

In the JS Part:

viewRegistry.add('error', 'error', ErrorPage);

Then your error page should get rendered.

DanielRuf commented 10 months ago

Unfortunately the error.html.twig approach didn't cover our usecase which requires the navigations, header, footer and more parts of the main template, render these around the error page content and do all that without page reload.

Before our current approach we tried to use error.html.twig, but we were missing things there (and in this case we didn't know about the json_encode solution, that you show).

To me it was the better solution to directly set the data in the error case, use the existing logic and combine it with the new error view in React directly.

So we probably have two different solutions which cover the same problem. I let you decide which one is better. Personally I found my solution better, because it sets the needed data earlier in the JavaScript logic and where the other data is also normally set (the error case was not covered there with setData()).

Feel free to close this issue if not relevant.