Skip to content

Commit b456f00

Browse files
authored
fix: Fall back to InternalServerError when error view rendering fails (#23177)
Prevents navigation corruption when error view's parent layout throws an exception during afterNavigation by catching the exception and rendering InternalServerError as fallback. Fixes #22146
1 parent 7e08652 commit b456f00

3 files changed

Lines changed: 136 additions & 50 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/component/UI.java‎

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@
7373
import com.vaadin.flow.router.Router;
7474
import com.vaadin.flow.router.RouterLayout;
7575
import com.vaadin.flow.router.internal.ErrorStateRenderer;
76-
import com.vaadin.flow.router.internal.ErrorTargetEntry;
7776
import com.vaadin.flow.router.internal.HasUrlParameterFormat;
7877
import com.vaadin.flow.router.internal.PathUtil;
7978
import com.vaadin.flow.server.Command;
@@ -2045,38 +2044,14 @@ private void handleNavigation(Location location,
20452044
adjustPageTitle();
20462045

20472046
} catch (Exception exception) {
2048-
handleExceptionNavigation(location, exception);
2047+
getInternals().getRouter().handleExceptionNavigation(this, location,
2048+
exception, NavigationTrigger.CLIENT_SIDE,
2049+
(BaseJsonNode) null);
20492050
} finally {
20502051
getInternals().clearLastHandledNavigation();
20512052
}
20522053
}
20532054

2054-
private boolean handleExceptionNavigation(Location location,
2055-
Exception exception) {
2056-
Optional<ErrorTargetEntry> maybeLookupResult = getInternals()
2057-
.getRouter().getErrorNavigationTarget(exception);
2058-
if (maybeLookupResult.isPresent()) {
2059-
ErrorTargetEntry lookupResult = maybeLookupResult.get();
2060-
2061-
ErrorParameter<?> errorParameter = new ErrorParameter<>(
2062-
lookupResult.getHandledExceptionType(), exception,
2063-
exception.getMessage());
2064-
ErrorStateRenderer errorStateRenderer = new ErrorStateRenderer(
2065-
new NavigationStateBuilder(getInternals().getRouter())
2066-
.withTarget(lookupResult.getNavigationTarget())
2067-
.build());
2068-
2069-
ErrorNavigationEvent errorNavigationEvent = new ErrorNavigationEvent(
2070-
getInternals().getRouter(), location, this,
2071-
NavigationTrigger.CLIENT_SIDE, errorParameter);
2072-
2073-
errorStateRenderer.handle(errorNavigationEvent);
2074-
} else {
2075-
throw new RuntimeException(exception);
2076-
}
2077-
return isPostponed();
2078-
}
2079-
20802055
private boolean isPostponed() {
20812056
return getInternals().getContinueNavigationAction() != null;
20822057
}

‎flow-server/src/main/java/com/vaadin/flow/router/Router.java‎

Lines changed: 68 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.util.Map;
2020
import java.util.Optional;
2121

22+
import org.slf4j.Logger;
2223
import org.slf4j.LoggerFactory;
2324
import tools.jackson.databind.node.BaseJsonNode;
2425

@@ -283,29 +284,82 @@ private int handleNavigation(UI ui, Location location,
283284
"Couldn't find route for '" + location.getPath() + "'");
284285
}
285286

286-
private int handleExceptionNavigation(UI ui, Location location,
287+
/**
288+
* Render error view for exception. Finds view to render based on the
289+
* exception type. Exception view is chosen for matching exception and if no
290+
* match is found choose by extended type.
291+
* <p>
292+
* For internal use only. May be renamed or removed in a future release.
293+
*
294+
* @param ui
295+
* current UI instance
296+
* @param location
297+
* target location for failing navigation
298+
* @param exception
299+
* exception thrown
300+
* @param trigger
301+
* navigation trigger
302+
* @param state
303+
* navigation state info
304+
* @return the HTTP status code to return to the client if handling an
305+
* initial rendering request
306+
*/
307+
public int handleExceptionNavigation(UI ui, Location location,
287308
Exception exception, NavigationTrigger trigger,
288309
BaseJsonNode state) {
289310
Optional<ErrorTargetEntry> maybeLookupResult = getErrorNavigationTarget(
290311
exception);
291312

292-
if (maybeLookupResult.isPresent()) {
293-
ErrorTargetEntry lookupResult = maybeLookupResult.get();
313+
if (maybeLookupResult.isEmpty()) {
314+
// No error target available throw runtime exception
315+
// this is usually only possible when routeRegistry is not
316+
// ApplicationRouteRegistry
317+
String message = String.format(
318+
"No error view found for exception '%s'",
319+
exception.getClass().getName());
320+
throw new RuntimeException(message, exception);
321+
}
294322

295-
ErrorParameter<?> errorParameter = new ErrorParameter<>(
296-
lookupResult.getHandledExceptionType(), exception,
297-
exception.getMessage());
298-
ErrorStateRenderer handler = new ErrorStateRenderer(
299-
new NavigationStateBuilder(this)
300-
.withTarget(lookupResult.getNavigationTarget())
301-
.build());
323+
ErrorTargetEntry lookupResult = maybeLookupResult.get();
324+
325+
ErrorParameter<?> errorParameter = new ErrorParameter<>(
326+
lookupResult.getHandledExceptionType(), exception,
327+
exception.getMessage());
328+
ErrorStateRenderer handler = new ErrorStateRenderer(
329+
new NavigationStateBuilder(this)
330+
.withTarget(lookupResult.getNavigationTarget())
331+
.build());
302332

303-
ErrorNavigationEvent navigationEvent = new ErrorNavigationEvent(
304-
this, location, ui, trigger, errorParameter, state);
333+
ErrorNavigationEvent navigationEvent = new ErrorNavigationEvent(this,
334+
location, ui, trigger, errorParameter, state);
305335

336+
try {
306337
return handler.handle(navigationEvent);
307-
} else {
308-
throw new RuntimeException(exception);
338+
} catch (Exception errorHandlingException) {
339+
Logger logger = LoggerFactory.getLogger(Router.class);
340+
341+
// Error view threw an exception - fall back to
342+
// InternalServerError
343+
logger.error(
344+
"Exception occurred while rendering error view '{}' for '{}'. "
345+
+ "Falling back to InternalServerError.",
346+
lookupResult.getNavigationTarget(), location.getPath(),
347+
errorHandlingException);
348+
349+
// Render InternalServerError as fallback with original
350+
// exception as render error is logged
351+
ErrorParameter<?> fallbackParameter = new ErrorParameter<>(
352+
Exception.class, exception, exception.getMessage());
353+
ErrorStateRenderer fallbackHandler = new ErrorStateRenderer(
354+
new NavigationStateBuilder(this)
355+
.withTarget(InternalServerError.class).build());
356+
357+
ErrorNavigationEvent fallbackEvent = new ErrorNavigationEvent(this,
358+
location, ui, trigger, fallbackParameter, state);
359+
360+
// If InternalServerError also throws, let it propagate -
361+
// nothing more we can do
362+
return fallbackHandler.handle(fallbackEvent);
309363
}
310364
}
311365

‎flow-server/src/test/java/com/vaadin/flow/router/RouterTest.java‎

Lines changed: 65 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2981,14 +2981,11 @@ public void exception_in_exception_handler_while_navigating_should_clear_last_ha
29812981
setNavigationTargets(FailOnException.class);
29822982
setErrorNavigationTargets(FailingErrorHandler.class);
29832983

2984-
try {
2985-
ui.navigate("exception");
2986-
Assert.fail("No runtime exception was thrown from navigation");
2987-
} catch (Exception re) {
2988-
Assert.assertNull(
2989-
"Last handled location should have been cleared even though navigation failed",
2990-
ui.getInternals().getLastHandledLocation());
2991-
}
2984+
ui.navigate("exception");
2985+
2986+
Assert.assertNull(
2987+
"Last handled location should have been cleared even though navigation failed",
2988+
ui.getInternals().getLastHandledLocation());
29922989
}
29932990

29942991
@Test
@@ -4697,4 +4694,64 @@ private void navigate(String url) {
46974694
router.navigate(ui, new Location(url), NavigationTrigger.PROGRAMMATIC);
46984695
}
46994696

4697+
// Test classes for exception in error view's parent layout afterNavigation
4698+
@Tag(Tag.DIV)
4699+
@Layout
4700+
public static class ThrowingMainLayout extends Component
4701+
implements RouterLayout, AfterNavigationObserver {
4702+
4703+
static List<AfterNavigationEvent> events = new ArrayList<>();
4704+
4705+
@Override
4706+
public void afterNavigation(AfterNavigationEvent event) {
4707+
events.add(event);
4708+
throw new RuntimeException(
4709+
"Exception in MainLayout afterNavigation");
4710+
}
4711+
}
4712+
4713+
@Route(value = "error", layout = ThrowingMainLayout.class)
4714+
@Tag(Tag.DIV)
4715+
public static class TriggerErrorView extends Component {
4716+
}
4717+
4718+
@Tag(Tag.DIV)
4719+
@ParentLayout(ThrowingMainLayout.class)
4720+
public static class ErrorViewWithThrowingLayout extends Component
4721+
implements HasErrorParameter<RuntimeException> {
4722+
4723+
@Override
4724+
public int setErrorParameter(BeforeEnterEvent event,
4725+
ErrorParameter<RuntimeException> parameter) {
4726+
getElement().setText("An unexpected error occurred");
4727+
return HttpStatusCode.INTERNAL_SERVER_ERROR.getCode();
4728+
}
4729+
}
4730+
4731+
@Test
4732+
public void exception_in_error_view_parent_layout_afterNavigation_falls_back_to_InternalServerError()
4733+
throws InvalidRouteConfigurationException {
4734+
ThrowingMainLayout.events.clear();
4735+
setNavigationTargets(TriggerErrorView.class);
4736+
setErrorNavigationTargets(ErrorViewWithThrowingLayout.class);
4737+
4738+
int result = router.navigate(ui, new Location("error"),
4739+
NavigationTrigger.PROGRAMMATIC);
4740+
4741+
Assert.assertEquals(
4742+
"Navigation should complete with internal server error status.",
4743+
HttpStatusCode.INTERNAL_SERVER_ERROR.getCode(), result);
4744+
4745+
// Should fall back to InternalServerError instead of the custom error
4746+
// view
4747+
assertExceptionComponent(InternalServerError.class,
4748+
"There was an exception while trying to navigate to 'error' with the exception message 'Exception in MainLayout afterNavigation'");
4749+
4750+
// Verify that MainLayout's afterNavigation was called two times.
4751+
// Once for navigation and once for error view.
4752+
Assert.assertEquals(
4753+
"MainLayout's afterNavigation should have been called twice", 2,
4754+
ThrowingMainLayout.events.size());
4755+
}
4756+
47004757
}

0 commit comments

Comments
 (0)