somoly.tistory.com
article thumbnail
Published 2019. 7. 4. 14:02
404 NoHandlerFoundException 설정 SpringBoot

404 에러를 사용자가 커스텀 하게 구성하여 사용하고자 할 경우 아래와 같이 설정하여 사용할 수 있습니다.

 

테스트 환경 : JDK 11 이상, SpringBoot 2.5.x

 

없는 페이지 테스트 URL : http://localhost:8080/hello

 

pom.xml 에 필요한 패키지

<html />
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

 

Springboot404Application.java

<java />
package rxcats.springboot404; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Springboot404Application { public static void main(String[] args) { SpringApplication.run(Springboot404Application.class, args); } }

 

먼저 아무 설정이 없을 경우 없는 페이지를 요청할 경우 웹페이지에서는 아래와 같은 페이지를 볼 수 있습니다.

 

<html />
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sat Sep 25 04:27:55 KST 2021 There was an unexpected error (type=Not Found, status=404).

 

curl 로 호출하면 아래와 같은 에러를 만날 수 있습니다.

curl -H "Content-Type: application/json" http://localhost:8080/hello

 

<javascript />
{"timestamp":"2021-09-24T19:34:00.219+00:00","status":404,"error":"Not Found","path":"/hello"}

 

이제 에러 페이지를 위한 코드를 추가해 보겠습니다.

 

application.properties 파일에 아래 설정을 추가 합니다.

<html />
spring.mvc.throw-exception-if-no-handler-found=true spring.web.resources.add-mappings=false

 

@RestControllerAdvice 를 이용하여 InternalErrorControllerAdvice 를 구현하도록 합니다.

Request 의 Content-Type 항목을 이용하여 application/json 인 경우 json 으로 반환을 하도록 하고 아니면 text 로 반환하도록 설정합니다.

InternalErrorControllerAdvice.java

<html />
package rxcats.springboot404; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import java.util.Map; import java.util.Objects; @RestControllerAdvice public class InternalErrorControllerAdvice { @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) { if (Objects.equals(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) { Map<String, Object> body = Map.of("error", "Not Found", "timestamp", System.currentTimeMillis()); return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); } return new ResponseEntity<>("Not Found", HttpStatus.NOT_FOUND); } }

 

웹페이지로 다시 호출하게 되면 아래와 같은 텍스트를 만날 수 있습니다.

<javascript />
Not Found

 

curl 로 호출하면 아래와 같은 에러를 만날 수 있습니다.

curl -H "Content-Type: application/json" http://localhost:8080/hello

<javascript />
{"error":"Not Found","timestamp":1632512269920}

 

이제 상황에 따라 handlerError Method 를 수정하여 사용하면 됩니다.

 

 

SpringBoot 의 ErrorController 의 자동설정소스를 확인하고 싶으시면 아래 소스코드를 확인해 보시면 됩니다.

org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController

org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController

 

'SpringBoot' 카테고리의 다른 글

Spring 6 의 HTTP Interface  (0) 2023.03.14
Retrying Feign Calls  (0) 2023.03.14
RedisTemplate 과 Json Serializer 설정  (0) 2019.07.09
MongoDB _class 필드 제거하기  (0) 2019.07.09
restful json request response 패킷 로깅 필터  (1) 2019.07.04
profile

somoly.tistory.com

@RxCats

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!