Let's create a TODO application in Java 11 Exception handling when accessing TODO with a non-existent ID

Hello.

This is a series of making TODO applications with Java + Spring, but from this time we will finally implement exception handling.

I want to start from a relatively easy place to get used to exception handling, so let's take a look at exception handling when accessing a non-existent ID!

TODO application creation link collection

1: [Understanding super basics] A brief description of MVC 2: [Prepare a template] I want to create a template with Spring Initializr and do Hello world 3: [Connection / Settings / Data display with MySQL] Save temporary data in MySQL-> Get all-> Display on top 4: [POST function] Implementation of posting function 5: [PATCH function] Switch TODO display 6: [Easy to use JpaRepository] Implementation of search function [7: [Common with Thymeleaf template fragment] Create Header] (https://qiita.com/nomad_kartman/items/8c33eca2880c43a06e40) [8: [PUT function] Implementation of editing function] (https://qiita.com/nomad_kartman/items/66578f3f91a422f9207d) [9: [Tweak] Sort TODO display in chronological order + Set due date default to today's date] (https://qiita.com/nomad_kartman/items/5ee2b13a701cf3eaeb15) 10: [Exception handling with spring] A brief summary of exception handling 11: [Exception handling with spring] Exception handling when accessing TODO with non-existent ID (now here)

Think about how exception handling is handled

Now, in the previous article, I briefly explained what exception handling is.

In summary

Security by directing to a specific error page when the user makes an unintended request of the creator (entering more characters than specified when registering TODO, trying to access a non-existent URL ... etc) Improve surface and usability.

It means that.

Exception handling flow

This time we will implement it when ** requesting access to TODO with non-existent ID ** ...

First, check the controller

com/example/todo/TodoController.java


    @GetMapping("/edit/{id}")
    public String showEdit(Model model, @PathVariable("id") long id ) {
        TodoEntity editTarget = todoService.findTodoById(id);
        model.addAttribute( "editTarget" , editTarget);
        return "edit";
    }

Exception handling when calling this showEdit. todoService.findTodoById (id) gets TODO via the Service class, but let's take a look at findTodoById ().

Check findTodoById () of Service class

com/example/todo/TodoService.java


    public TodoEntity findTodoById(Long todoId) {
        Optional<TodoEntity> todoResult = todoRepository.findById(todoId);
        return todoResult.get();
    }

ID search is performed from Repository, TODO is acquired and returned as Optional type.

However, if you try to search with an ID that does not exist here, it will fail with an error, so at this timing

** If todoResult is empty, lead to a specific Exception class **

You should do it!

Specific Exception class?

com/example/todo/exception/TodoNotFoundException.java


package com.example.todo.exception;
public class TodoNotFoundException extends RuntimeException{
}

Create a new directory called `ʻexceptionand create a class called TodoNotFoundException`` in it.

`ʻextendsmeans that this class inherits from RuntimeException. By inheriting, the method of RunttimeException`` can be used in this class as well. (I will not use it this time ...)

Direct to TodoNotFoundException class when todoResult is empty in findTodoById ()

com/example/todo/TodoService.java


    public TodoEntity findTodoById(Long todoId) {
        Optional<TodoEntity> todoResult = todoRepository.findById(todoId);
        todoResult.orElseThrow(TodoNotFoundException::new);
        return todoResult.get();
    }

Let's take a look at the line we added before return!

By setting ʻOptional.orElseThrow (Exception name :: new) `, you can skip the process to the specified class when the Optional type is empty. (This time, the TodoNotFoundException that I made earlier)

By the way, the part of `ʻException name :: new`` is called a method reference, and it refers to the method as an argument of the method.

This article will be helpful, so please take a look.

Create a class that manages TodoNotFoundException.

The TodoNotFoundException you created earlier just inherited the RuntimeException and the contents were empty.

com/example/todo/exception/TodoNotFoundException.java


package com.example.todo.exception;
public class TodoNotFoundException extends RuntimeException{
}

Here, using the annotation @ControllerAdvice, we will implement the processing ** when ** TodoNotFoundException is called (= when thrown) **.

com/example/todo/exception/TodoControllerAdvice.java


package com.example.todo.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@Slf4j
@ControllerAdvice
public class TodoControllerAdvice {
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(TodoNotFoundException.class)
    public String idNotFound() {
        log.warn("The specified TODO cannot be found.");
        return "error/404.html";
    }
}

Let's create a class like this in the `ʻexception`` directory.

To explain in order from the top ...

@Slf4j
By using this annotation, you can display the log. You can view the logs in the terminal with log.warn ("contents") or log.info ("contents").
@ControllerAdvice
Indicates that this class is ControllerAdvice. You will be able to set what to do when an exception occurs in TodoController.
@ResponseStatus(HttpStatus.NOT_FOUND)
Returns HttpStatus as Not_Found.
@ExceptionHandler(TodoNotFoundException.class)
This is important, but by using this annotation, when TodoNotFoundException occurs in the processing in TodoController, this idNotFound () is specified to be processed. In this function, error / 404.html is displayed while outputting the error log.

Creating an error page

templates/error/404.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404</title>
</head>
<body>
404!
</body>
</html>

Normally, the error content should be displayed, but this time it's simply 404! I just want to display.

Summary of the flow of exception handling implemented this time

It may be confusing because I explained it all at once, but the following is a summary of this process.

-User requests Todo editing (800 / edit / 100)

-The controller sends processing to the service class upon request (findTodoById (100))

-Since there is no TODO with ID = 100, TodoNotFoundException is called.

- TodoControllerAdvice with @ControllerAdvice outputs a log saying "The specified TODO cannot be found" and transitions to 404.html.

It is like this!

It may be a little difficult to understand if it is a sentence, so I think you should read the article here.

We will continue to implement exception handling next time!

Recommended Posts

Let's create a TODO application in Java 11 Exception handling when accessing TODO with a non-existent ID
Let's create a TODO application in Java 6 Implementation of search function
Let's create a TODO application in Java 1 Brief explanation of MVC
Let's create a TODO application in Java 5 Switch the display of TODO
Let's create a TODO application in Java 12 Processing when a request comes in with an unused HttpMethod ・ Processing when an error occurs in the server
Let's make a calculator application with Java ~ Create a display area in the window
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
Create a TODO app in Java 7 Create Header
Let's create a TODO application in Java 13 TODO form validation 1: Character limit ・ Gradle update to use @Validated
Let's create a TODO application in Java 3 Save temporary data in MySQL-> Get all-> Display on top
Create a CSR with extended information in Java
Let's create a timed process with Java Timer! !!
Let's create a super-simple web framework in Java
Let's create a TODO application in Java 9 Create TODO display Sort by date and time + Set due date default to today's date
Exception handling techniques in Java
Let's make a calculator application in Java ~ Display the application window
Create a SlackBot with AWS lambda & API Gateway in Java
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
I can't create a Java class with a specific name in IntelliJ
Exception handling with a fluid interface
Let's go with Watson Assistant (formerly Conversation) ⑤ Create a chatbot with Watson + Java + Slack
Create a java web application development environment with docker for mac part2
Create a simple web application with Dropwizard
Let's create a Java development environment (updating)
Split a string with ". (Dot)" in Java
Let's create a versatile file storage (?) Operation library by abstracting file storage / acquisition in Java
Read a string in a PDF file with Java
Create a simple bulletin board with Java + MySQL
[Windows] [IntelliJ] [Java] [Tomcat] Create a Tomcat9 environment with IntelliJ
Try to create a bulletin board in Java
Let's create a custom tab view in SwiftUI 2.0
[Java] Create a collection with only one element
A note when you want Tuple in Java
[Java] Let's create a mod for Minecraft 1.14.4 [Introduction]
[Java] Let's create a mod for Minecraft 1.14.4 [99. Mod output]
Questions in java exception handling throw and try-catch
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
A memo when I tried "Talking about writing a Java application in Eclipse and publishing it in Kubernetes with a Liberty container (Part 1)"
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
[Java] Let's create a mod for Minecraft 1.14.4 [0. Basic file]
[Java] Consideration when handling negative binary numbers with Integer.parseInt ()
[Java] Let's create a mod for Minecraft 1.14.4 [4. Add tools]
How to create a Java environment in just 3 seconds
[Java] Let's create a mod for Minecraft 1.14.4 [5. Add armor]
[Java] Let's create a mod for Minecraft 1.14.4 [Extra edition]
[Java] Let's create a mod for Minecraft 1.14.4 [7. Add progress]
[Java] Let's create a mod for Minecraft 1.14.4 [6. Add recipe]
[Java] Let's create a mod for Minecraft 1.16.1 [Add item]
[Java] Let's create a mod for Minecraft 1.16.1 [Basic file]
[Java basics] Let's make a triangle with a for statement
[Java] Let's create a mod for Minecraft 1.14.4 [1. Add items]
How to create a data URI (base64) in Java
Quickly implement a singleton with an enum in Java
[Note] Create a java environment from scratch with docker
What I learned when building a server in Java
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
[Java] Let's create a mod for Minecraft 1.14.4 [2. Add block]
Create a JAVA WEB application and try OMC APM