skill/Java.Kotlin

Springboot @RequestParam null 일 경우, exception handler 처리

have a nice day :D 2023. 1. 31. 14:48
반응형

springboot restcontroller requestparam 설정

@GetMapping(value = "/test")
public Map<String, Object> accounts(
        @RequestParam(value = "code") String code,
        @RequestParam(value = "page" , required = false, defaultValue = "0") int page,
        @RequestParam Map<String, Object> req) throws Exception {

@RequestParam 필수값 exception handler 
잘못된 예

@ControllerAdvice
@RestController
public class ResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Object handleValidationExceptions(
            Exception ex) {
        return ex.getMessage()

    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Object handleMissingServletRequestParameterException(
            MissingServletRequestParameterException ex) {
        return "parameter is null : " + ex.getParameterName()
    }
}

기동에러
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handlerExceptionResolver' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation...5.3.25.jar:5.3.25]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; 
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MissingServletRequestParameterException]:

에러 발생 사유
ResponseEntityExceptionHandler 에 
@ExceptionHandler(MissingServletRequestParameterException.class)를 처리 하고 있어서

에러 수정

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

@Slf4j
@ControllerAdvice
@RestController
public class ResponeExceptionHandler  {

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public String handleMissingServletRequestParameterException(
            MissingServletRequestParameterException ex) {
        return "paramer is null : " + ex.getParameterName();
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleAllExceptions(Exception ex) {
        return ex.getMessage();
    }
}


extends ResponseEntityExceptionHandler 클래스와 함께 사용하면 안됨.

반응형