404 NoHandlerFoundException 설정

2019. 7. 4. 14:02·SpringBoot

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

 

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

 

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

 

pom.xml 에 필요한 패키지

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

 

Springboot404Application.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);
    }

}

 

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

 

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

 

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

 

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

 

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

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

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);
    }

}

 

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

Not Found

 

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

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

{"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
'SpringBoot' 카테고리의 다른 글
  • Retrying Feign Calls
  • RedisTemplate 과 Json Serializer 설정
  • MongoDB _class 필드 제거하기
  • restful json request response 패킷 로깅 필터
somoly
somoly
About me.
  • somoly
    somoly.tistory.com
    somoly
  • 전체
    오늘
    어제
    • 전체 (55)
      • SpringBoot (8)
      • Kotlin (5)
      • Javascript (4)
      • 백엔드 (6)
      • Linux (25)
      • Windows (1)
      • IT (2)
      • FF14 (1)
      • 애니 (1)
      • Figure (1)
      • 회사생활 (1)
  • 블로그 메뉴

    • HOME
    • TAGS
    • MEDIA
    • LOCATION
    • GUESTBOOK
    • ADMIN
    • WRITE
  • 링크

    • [FF14] 5.0 (71-80) 제작 레벨링 매크로
    • [FF14] 갈론드벨
    • [FF14] FFLogs
    • [FF14] Ariyala 장비 시뮬레이터
    • [FF14] 낚시 도우미
    • [FF14] 인테리어 정보
    • [FF14] 의상 코디 정보
  • 공지사항

  • 인기 글

  • 태그

    accesskey
    dynamodb local
    83인치
    jvminline
    interactive table
    종료
    30일전
    77인치
    ubuntu
    string methods
    부팅
    Kotlin
    exchage method
    bcmod
    동영상
    tabulator
    설치
    우분투
    피규어
    springboot
    최후의 재림
    Spring
    javascript
    P2P
    VirtualBox
    리눅스
    utf-8
    HTTP
    versioncomapre
    linux
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
somoly
404 NoHandlerFoundException 설정
상단으로

티스토리툴바