Customize REST API error response with Spring Boot (Part 2)

Overview

I tried to customize the response at the time of error with Spring Boot, so I will describe it here as a memorandum. In Previous article, I defined an original exception and tried to handle the exception, but this time Spring defines an exception. I would like to describe the handle of.

Background

I was able to catch the original exception defined in the previous article, but when the exception defined by Spring at the beginning of the MethodArgumentNotValidException exception occurred, the error content was returned with null body part. This time, I will summarize the cause and countermeasure policy.

Prerequisites

environment

Cause

"A thorough introduction to Spring Java application development with Spring Framework" states as follows. I will quote below.

ResponseEntityExceptionHandler implements @ExceptionHandler method that handles exceptions that occur in Spring MVC framework processing. In other words, you can handle all the exceptions that occur in the framework processing just by creating a class like the one above. If you just create a class that inherits the ResponseEntityExceptionHandler class, the response body will respond with an error in the state of. If you just create a class that inherits ResponseEntityExceptionHandler, the response body will respond empty. Override the handleExceptionInternal method if you want to output error information to the response body.

Now we know the direct cause. In Previous article, handle handling for original exceptions was implemented, but handle handling is defined for exceptions defined by Spring. I think that the body part was blanked even if an exception occurred because it was not. (= At the stage of defining the handle class that inherits ResponseEntityExceptionHandler, it seems that you have to define the handle method not only for your own exception but also when other exceptions occur. I'm not very familiar with this area. Please tell me the details ...)

This time, I checked it in the code base.

If you check the handleMethodArgumentNotValid method that handles theMethodArgumentNotValidExceptionof the parent class ResponseEntityExceptionHadler class, null is explicitly passed to the body part, and when you debug, this process is passed.

ResponseEntityExceptionHadler.java


protected ResponseEntity<Object> handleMethodArgumentNotValid(
			MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

	return handleExceptionInternal(ex, null, headers, status, request);
}

For the content and order of the arguments of handleExceptionInternal, refer to Previous article.

Correspondence policy

As you can see from the above, null is explicitly passed to the body part of the method argument, so if you override this method and pass the error content you actually want to display to the body part, it should be displayed. is. Then, I would like to actually move it.

Controller definition

HelloSpringExceptionController.java


package com.example.demo.springExceptionErrorResponse;

import com.example.demo.errorResponse.ErrorDetail;
import com.example.demo.errorResponse.MyException;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/springexceptionhandle")
public class HelloSpringExceptionController {

    @RequestMapping("/test")
    public void get(@RequestBody @Validated Person person, Model model) {
    }
}

Model class definition

Person.java


package com.example.demo.springExceptionErrorResponse;

import lombok.Data;

import javax.validation.constraints.NotNull;

@Data
public class Person {
    @NotNull
    String firstName;
    @NotNull
    String lastName;
}

Exception handler class definition

This time I simply passed the string " It's an error. " `. Regarding this, please define it as you like by defining a class for the body at the time of error.

SpringExceptionHandler.java


package com.example.demo.springExceptionErrorResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@RestControllerAdvice
public class SpringExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(
            Exception ex,
            Object object,
            HttpHeaders headers,
            HttpStatus status,
            WebRequest request) {
        return super.handleExceptionInternal(ex, "It's an error.", headers, status, request);
    }
}

Run

Below, try requesting JSON from http: // localhost: 8080 / springexceptionhandle / test with POST. This request should result in an error because Person.java has a @NotNull constraint applied to firstName.

input.json


{
  "firstName": null,
  "lastName": "name"
}

result

It's an error.

The above is lonely as a response body, but if you want to display the time when an error occurs, status code, etc., respond like Previous article You should be able to see it by defining a body-specific class and passing an instance of that class as the second argument to the super.handleExceptionInternal method.

Related article

Customize REST API error response with Spring Boot (Part 1)

Reference article

This time, I referred to the following article when writing the article.

[Thorough introduction to Spring Java application development with Spring Framework](https://www.amazon.co.jp/Spring%E5%BE%B9%E5%BA%95%E5%85%A5%E9%96%80- Spring-Framework% E3% 81% AB% E3% 82% 88% E3% 82% 8BJava% E3% 82% A2% E3% 83% 97% E3% 83% AA% E3% 82% B1% E3% 83% BC% E3% 82% B7% E3% 83% A7% E3% 83% B3% E9% 96% 8B% E7% 99% BA-% E6% A0% AA% E5% BC% 8F% E4% BC% 9A % E7% A4% BENTT% E3% 83% 87% E3% 83% BC% E3% 82% BF / dp / 4798142476) Customize the error response of REST API created by Spring Boot Error handling with Spring Boot Handling exceptions with @ RestController of Spring Boot

Recommended Posts

Customize REST API error response with Spring Boot (Part 2)
Customize REST API error response with Spring Boot (Part 1)
Hello World (REST API) with Apache Camel + Spring Boot 2
[Spring Boot] Get user information with Rest API (beginner)
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Spring with Kotorin --4 REST API design
REST API test with REST Assured Part 2
Implement REST API in Spring Boot
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Implement REST API with Spring Boot and JPA (domain layer)
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Implement a simple Web REST API server with Spring Boot + MySQL
Change Spring Boot REST API request / response from CamelCase to SankeCase
[Beginner] Let's write REST API of Todo application with Spring Boot
Create a web api server with spring boot
Download with Spring Boot
I created an api domain with Spring Framework. Part 2
Automatically map DTOs to entities with Spring Boot API
Extend Spring Boot DefaultErrorViewResolver to dynamically customize error screens
A memorandum when creating a REST service with Spring Boot
I created an api domain with Spring Framework. Part 1
Introduce swagger-ui to REST API implemented in Spring Boot
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
REST API testing with REST Assured
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Link API with Spring + Vue.js
Introduction to Spring Boot Part 1
Create microservices with Spring Boot
Send email with spring boot
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Try hitting the zip code search API with Spring Boot
Let's find out how to receive in Request Body with REST API of Spring Boot
Use Basic Authentication with Spring Boot
Let's make a book management web application with Spring Boot part1
gRPC on Spring Boot with grpc-spring-boot-starter
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Let's make a book management web application with Spring Boot part3
Spring Boot: Restful API sample project
Spring Boot programming with VS Code
Inquiry application creation with Spring Boot
Part 1: Try using OAuth 2.0 Login supported by Spring Security 5 with Spring Boot
How to create your own Controller corresponding to / error with Spring Boot
Let's make a book management web application with Spring Boot part2
Get validation results with Spring Boot
spring boot access authorization RESTful API
I made a simple search form with Spring Boot + GitHub Search API.