Groovy / Maven

Error Handling

Learn about error handling in the Micronaut framework.

Sergio del Amo
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Groovy.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide --build=maven --lang=groovy
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

Global @Error

We want to display a custom Not Found page when the user attempts to access a URI that has no defined routes.

notfound

The views module provides support for view rendering on the server side and does so by rendering views on the I/O thread pool in order to avoid blocking the Netty event loop.

To use the view rendering features described in this section, add the following dependency on your classpath. Add the following dependency to your build file:

pom.xml
<dependency>
    <groupId>io.micronaut.views</groupId>
    <artifactId>micronaut-views-velocity</artifactId>
    <scope>compile</scope>
</dependency>

The Micronaut framework ships out-of-the-box with support for Apache Velocity, Thymeleaf or Handlebars. In this guide, we use Apache Velocity.

Create a notFound.vm view:

src/main/resources/views/notFound.vm
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Not Found</title>
</head>
<body>
<h1>NOT FOUND</h1>

<p><b>The page you were looking for appears to have been moved, deleted or does not exist.</b></p>

<p>This is most likely due to:</p>

<ul>
    <li>An outdated link on another site</li>
    <li>A typo in the address / URL</li>
</ul>
</body>
</html>

Create a NotFoundController:

groovy/src/main/groovy/example/micronaut/NotFoundController.groovy

Local @Error

Micronaut validation is built on the standard framework – JSR 380, also known as Bean Validation 2.0. Micronaut Validation has built-in support for validation of beans that are annotated with jakarta.validation annotations.

To use Micronaut Validation, you need the following dependencies:

pom.xml
<dependency>
    <groupId>io.micronaut.validation</groupId>
    <artifactId>micronaut-validation-processor</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>io.micronaut.validation</groupId>
    <artifactId>micronaut-validation</artifactId>
    <scope>compile</scope>
</dependency>

Alternatively, you can use Micronaut Hibernate Validator, which uses Hibernate Validator; a reference implementation of the validation API.

Then create a view to display a form:

createbook
src/main/resources/views/bookscreate.vm
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Create Book</title>
    <style type="text/css">
        form fieldset li {
            list-style-type: none;
        }
        #errors span { color: red; }
    </style>
</head>
<body>
<h1>Create Book</h1>
<form action="/books/save" method="post">
    <fieldset>
        <ol>
            <li>
                <label for="title">Title</label>
                <input type="text" id="title" name="title" value="$title"/>
            </li>
            <li>
                <label for="pages">Pages</label>
                <input type="text" id="pages" name="pages" value="$pages"/>
            </li>
            <li>
                <input type="submit" value="Save"/>
            </li>
        </ol>
    </fieldset>
</form>
#if( $errors )
    <ul id="errors">
        #foreach( $error in $errors )
            <li><span>$error</span></li>
        #end
    </ul>
#end
</body>
</html>

To use the serialization features described in this section, add the following dependency to your build file:

pom.xml
<dependency>
    <groupId>io.micronaut.serde</groupId>
    <artifactId>micronaut-serde-jackson</artifactId>
    <scope>compile</scope>
</dependency>

Create a controller to map the form submission:

groovy/src/main/groovy/example/micronaut/BookController.groovy

Create the POJO encapsulating the submission:

groovy/src/main/groovy/example/micronaut/CommandBookSave.groovy

When the form submission fails, we want to display the errors in the UI as the next image illustrates:

createbookserrors

An easy way to achieve it is to capture the jakarta.validation.ConstraintViolationException exception in a local @Error handler. Modify BookController.java:

src/main/groovy/example/micronaut/BookController.groovy

Create a jakarta.inject.Singleton to encapsulate the generation of a list of messages from a Set of ConstraintViolation:

groovy/src/main/groovy/example/micronaut/MessageSource.groovy
package example.micronaut

import groovy.transform.CompileStatic
import jakarta.inject.Singleton

import jakarta.validation.ConstraintViolation
import jakarta.validation.Path

@CompileStatic
@Singleton
class MessageSource {

    List<String> violationsMessages(Set<ConstraintViolation<?>> violations) {
        violations.collect {violationMessage(it) }
    }

    private String violationMessage(ConstraintViolation violation) {
        StringBuilder sb = new StringBuilder()
        Path.Node lastNode = lastNode(violation.propertyPath)
        if (lastNode) {
            sb << lastNode.name << ' '
        }
        sb << violation.message
        sb
    }

    private static Path.Node lastNode(Path path) {
        Path.Node lastNode = null
        for (final Path.Node node : path) {
            lastNode = node
        }
        return lastNode
    }
}

ExceptionHandler

Another mechanism to handle a global exception is to use an ExceptionHandler.

Modify the controller and add a method to throw an exception:

src/main/groovy/example/micronaut/BookController.groovy
groovy/src/main/groovy/example/micronaut/OutOfStockException.groovy
package example.micronaut

import groovy.transform.CompileStatic

@CompileStatic
class OutOfStockException extends RuntimeException {
}

Implement an ExceptionHandler, a generic hook for handling exceptions that occur during the execution of an HTTP request.

groovy/src/main/groovy/example/micronaut/OutOfStockExceptionHandler.groovy

Next Steps

Explore more features with Micronaut Guides.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).