Table of contents
1.
Router Exception Handling🧑‍💻
1.1.
Error Resolving🚧
1.2.
Custom Exception Handlers🌐
1.2.1.
Advanced Exception Handling Example🚀
1.3.
Rerouting to an Error View🎯
2.
Frequently Asked Questions❓
2.1.
What is router exception handling?
2.2.
What is the meaning of exception handling?
2.3.
Why do you need to handle the exception?
2.4.
What happens when you don't handle an exception?
2.5.
What is the difference between error and exception?
3.
Conclusion
Last Updated: Aug 13, 2025
Medium

Router Exception Handling

Author ANJU JAISWAL
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Router Exception Handling🧑‍💻

For exceptions involving navigation targets, Router Exception Handling offers exceptional support. An error view is displayed when a navigation-related unhandled exception is thrown.

  Router Exception Handling

Since they are displayed for arbitrary URLs, exception targets typically lack a specific @Route but function similarly to regular navigation targets.

Error Resolving🚧

The target of navigation errors is determined by the type of exception thrown during navigation.

To be used as Router Exception Handling targets during navigation, all classes that implement the HasErrorParameterT extends exception> interface are gathered at startup. RouteNotFoundError is an illustration of such a class. It is included by default in the framework and is used to fix issues with the Router's NotFoundException.

Example: When there is no target for the specified URL, RouteNotFoundError defines the default target for the NotFoundException Router Exception Handling

displayed.

@Tag(Tag.DIV)
public class RouteNotFoundError extends Component
      implements HasErrorParameter<NotFoundException> {

    @Override
    public int setErrorParameter(BeforeEnterEvent event,
          ErrorParameter<NotFoundException> parameter) {
        getElement().setText("Could not navigate to '"
                    + event.getLocation().getPath()
                    + "'");
        return HttpServletResponse.SC_NOT_FOUND;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

This displays the text specified in the setText() parameter and returns a 404 HTTP response.

Exceptions match in the following order:

  1. Because of exception
     
  2. Super type is an exception
     

Both the 404 RouteNotFoundError and the 500 InternalServerError are implemented by default for NotFoundException and java.lang.Exception, respectively.

Custom Exception Handlers🌐

The default Router Exception Handling handlers can be modified by extending them.

Example: Personalized "route not found" handler with personalized application layout

@ParentLayout(MainLayout.class)
public class CustomNotFoundTarget
        extends RouteNotFoundError {

    @Override
    public int setErrorParameter(BeforeEnterEvent event,
          ErrorParameter<NotFoundException> parameter) {
        getElement().setText(
                "My custom not found class!");
        return HttpServletResponse.SC_NOT_FOUND;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Note:

  • There can only be extending instances.
     
  • Exception targets may define ParentLayouts. As in standard navigation, BeforeNavigationEvent and AfterNavigationEvent are still sent.
     
  • There can only be one exception handler per exception.
     

Advanced Exception Handling Example🚀

The following example assumes a dashboard application that gathers and displays user widgets. Authenticated users can only view widgets that are protected.

The Widget will check for authentication upon creation and throw an AccessDeniedException if the collection incorrectly instantiates a ProtectedWidget.                               

Exceptions everywhere

The AccessDeniedExceptionHandler, which keeps the MainLayout and its menu bar but displays information that an exception has occurred, Router Exception Handling handles the unhandled exception that propagates during navigation.

@Route(value = "dashboard", layout = MainLayout.class)
@Tag(Tag.DIV)
public class Dashboard extends Component {
    public Dashboard() {
        init();
    }

    private void init() {
        getWidgets().forEach(this::addWidget);
    }

    public void addWidget(Widget widget) {
        // Implementation omitted
    }

    private Stream<Widget> getWidgets() {
        // Implementation omitted, gets faulty state
        // widget
        return Stream.of(new ProtectedWidget());
    }
}

public class ProtectedWidget extends Widget {
    public ProtectedWidget() {
        if (!AccessHandler.getInstance()
                .isAuthenticated()) {
            throw new AccessDeniedException(
                    "Unauthorized widget access");
        }
        // Implementation omitted
    }
}

@Tag(Tag.DIV)
public abstract class Widget extends Component {
    public boolean isProtected() {
        // Implementation omitted
        return true;
    }
}

@Tag(Tag.DIV)
@ParentLayout(MainLayout.class)
public class AccessDeniedExceptionHandler
    extends Component
    implements HasErrorParameter<AccessDeniedException>
{

    @Override
    public int setErrorParameter(BeforeEnterEvent event,
            ErrorParameter<AccessDeniedException>
                    parameter) {
        getElement().setText(
            "Tried to navigate to a view without "
            + "correct access rights");
        return HttpServletResponse.SC_FORBIDDEN;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Rerouting to an Error View🎯

You can employ one of the overloads for the rerouteToError() method. The exception class to target and, if necessary, a unique error message are all required to be added.

You can set a specific message using the rerouteToError(Exception, String) method if the rerouting method encounters an exception.

Example: Error view sample on the blog with a personalized message

@Tag(Tag.DIV)
public class BlogPost extends Component
        implements HasUrlParameter<Long> {

    @Override
    public void setParameter(BeforeEvent event,
            Long parameter) {
        removeAll();

        Optional<BlogRecord> record =
                getRecord(parameter);

        if (!record.isPresent()) {
            event.rerouteToError(
                  IllegalArgumentException.class,
                  getTranslation("blog.post.not.found",
                        event.getLocation().getPath()));
        } else {
            displayRecord(record.get());
        }
    }

    private void removeAll() {
        // NO-OP
    }

    private void displayRecord(BlogRecord record) {
        // NO-OP
    }

    public Optional<BlogRecord> getRecord(Long id) {
        // Implementation omitted
        return Optional.empty();
    }
}

@Tag(Tag.DIV)
public class FaultyBlogPostHandler extends Component
  implements HasErrorParameter<IllegalArgumentException>
{

    @Override
    public int setErrorParameter(BeforeEnterEvent event,
            ErrorParameter<IllegalArgumentException>
                    parameter) {
        Label message = new Label(
                parameter.getCustomMessage());
        getElement().appendChild(message.getElement());

        return HttpServletResponse.SC_NOT_FOUND;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Rerouting to an error view set up for an exception is possible from the BeforeEnterEvent and BeforeLeaveEvent.

Example: Reroute to the error view

public class AuthenticationHandler
        implements BeforeEnterObserver {
    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        Class<?> target = event.getNavigationTarget();
        if (!currentUserMayEnter(target)) {
            event.rerouteToError(
                    AccessDeniedException.class);
        }
    }

    private boolean currentUserMayEnter(
            Class<?> target) {
        // implementation omitted
        return false;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Frequently Asked Questions❓

What is router exception handling?

For exceptions involving navigation targets, the Router offers exceptional support. An error view is displayed when a navigation-related unhandled exception is thrown.

What is the meaning of exception handling?

Exception handling is known as responding to unwanted or unexpected events that occur while a computer program is running. Without this process, exceptions would interfere with a program's regular operation and cause it to crash. Exception handling deals with these events to prevent this from happening.

Why do you need to handle the exception?

To avoid any unexpected program termination, the exceptions should be handled. If the program is interrupted in the middle, it should continue running.

What happens when you don't handle an exception?

If you don't deal with an exception after it occurs, the program will end abruptly, and the code after the line where the exception occurred won't run.

What is the difference between error and exception?

The error denotes a problem primarily brought on by a lack of system resources. The problems that can occur during compile and runtime are the exceptions. Errors cannot be corrected once they have been made.

Conclusion

As we learned, Router provides exceptional support for navigation target exceptions. An error view is shown when an unhandled exception is thrown during navigation. If you don't handle exceptions, the program terminates abruptly, and the code past the line that caused the exception will not get executed.

Refer to our guided paths on Coding Ninjas Studio for aptitude preparation. Enroll in our courses like data analyticsdata sciencemachine learningdatabase management, etc. Refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!                                       

Thank You
Live masterclass