[JAVA] Spring Boot exception handling

Spring Boot exception handling

Overview

In SpringBoot, exceptions can be handled by multiple methods such as exception handling using the SpringMVC function, SpringBoot AutoConfiguration and exception handling using the embedded server. Although it is stated in Official Reference, the range and mechanism that can be handled are a little difficult to understand. So I will summarize the main methods.

Exception handling method

List

Function name layer
HandlerExceptionResolver SpringMVC
ErrorPage SpringBoot
ErrorController SpringBoot

HandlerExcepitonResolver HandlerExceptionResolver is an exception handling method that uses the functions of Spring MVC. Since it uses the SpringMVC function, it cannot be handled if an exception occurs in Filter or View.

A schematic diagram of handling is shown below. image.png

HandlerExceptionResolver has multiple implementation classes shown below by default. In the table below, enable / disable indicates whether it is enabled or disabled by the default setting of Spring Boot, and the ExceptionResolver that comes above has priority.

name of the class Effectiveness/Invalid function
ExceptionHandlerExceptionResolver Effectiveness @Exception handling is performed by the method to which ExceptionHandler is assigned.
ResponseStatusExceptionResolver Effectiveness @Handle when an exception class with ResponseStatus is generated
DefaultHandlerExceptionResolver Effectiveness Handle exception classes defined in Spring MVC
SimpleMappingExceptionResolver Invalid Map exception class and View directly

The following shows the exception handling method by the most orthodox `ʻExceptionHandlerExceptionResolver``.

Handling by ExceptionHandlerExceptionResolver

When an exception occurs, the method with the @ExceptionHandler annotation to which the meta information of the exception class that occurred is added is scanned, and the process is transferred.

The method with @ExceptionHandler can be defined in the class with @Controller or @ControllerAdvice as shown below.

ThrowExceptionController.java


@Controller
@RequestMapping("web")
public class ThrowExceptionController {
	
	@GetMapping("original")
	public void throwOriginalException() {
		throw new OriginalWebException("thrown in ThrowExceptionController");

	}
	
	@ExceptionHandler(OriginalWebException.class)
	public String handleOriginalWebException(OriginalWebException exception) {
		return "OriginalWebException.html";
	}

}

TransverseExceptionHandler.java


@ControllerAdvice
public class ThrowExceptionController {
	
	@ExceptionHandler(OriginalWebException.class)
	public String handleOriginalWebException(OriginalWebException exception) {
		return "OriginalWebException.html";
	}

}

In the case of @Controller, exception handling is possible only for exceptions that occur in the same Controller, but in the case of @ControllerAdvice, all Controllers can be handled across the board.

If both @Controller and @ControllerAdvice can be handled, the one given to @Controller has priority.

ErrorPage

ErrorPage in SpringBoot is almost the same as ErrorPage element defined in Web.xml of conventional SpringFW.

ErrorPage maps the status code or exception class to the path so that it can be handled. A schematic diagram is shown below. image.png

How to register ErrorPage can be done by creating an implementation class of ErrorPageRegistrar as shown below.

AddErrorPage.java



@Configuration
public class AddErrorPage implements ErrorPageRegistrar {

	@Override
	public void registerErrorPages(ErrorPageRegistry registry) {
		registry.addErrorPages(new ErrorPage(exception, path));

        // new ErrorPage(HttpStatusCode, path)But possible
	}
}

ErrorController ErrorController is an exception handling method provided by Spring Boot and is the most commonly used method of exception handling in Spring Boot. A schematic diagram is shown below. image.png

If the exceptions that occur in the SpringBoot application are not handled, they are all supposed to be dispatched to the / error path by the ErrorPage function described above. By default, / error is mapped to the BasicErrorController class, and handling is performed there.

In BasicErrorController, handling returns HTML or JSON depending on the request header. In the case of HTML, WhiteLabelErrorPage is returned, and the returned contents are specified by ```ErrorAttributes. In the case of JSON, `ʻErrorAttributes is returned.

To customize the handling method by ʻErrorController``, create an implementation class of ʻErrorController. Also, if you want to customize the returned contents, implement the `ʻErrorAttributes class.

Summary

For exception handling in SpringBoot application, basically use `ʻErrorController, and if you want to perform finer handling, use HandlerExceptionResolver``.

Recommended Posts

Spring Boot exception handling
Exception handling
Exception handling Exception
Java exception handling?
About exception handling
ruby exception handling
Challenge Spring Boot
Ruby exception handling
[Java] Exception handling
Spring Boot Form
☾ Java / Exception handling
Java exception handling
Spring Boot Memorandum
Java exception handling
gae + spring boot
SPRING BOOT learning record 01
Spring Boot + Heroku Postgres
About Ruby exception handling
Spring boot memo writing (1)
First Spring Boot (DI)
Spring Boot2 cheat sheet
Spring Boot Servlet mapping
Spring boot development-development environment-
Spring Boot learning procedure
Learning Spring Boot [Beginning]
Spring boot memo writing (2)
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
Classes that require exception handling
[Spring Boot] Environment construction (macOS)
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Java's first exception handling (memories)
Spring Boot on Microsoft Azure
Implement GraphQL with Spring Boot
[Java] Practice of exception handling [Exception]
[Spring] Controller exception output test
Get started with Spring boot
[Java] About try-catch exception handling
Hello World with Spring Boot!
Spring Boot 2 multi-project in Gradle
[Ruby] Exception handling in functions
[Spring Boot] Web application creation
spring boot port duplication problem
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring Boot Hot Swapping settings
[Java] Thymeleaf Basic (Spring Boot)
Java exception handling usage rules
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use