[Spring boot] request param exception restControllerAdvice에서 관리하기

하비·2024년 1월 6일

Spring boot

목록 보기
1/5

처음에 not blank로 처리해야하는 줄 알고,

@RequestParam 부분에 @NotBlank 붙이고,

BaseExceptionHandler에서 ConstraintViolationException.class, bindException.class 붙여보기도 하고…

그것도 안돼서

@Valid 붙여서

BaseExceptionHandler에서 MethodArgumentNotValidException.class 붙여보기도 했다…

근데 결국엔 에러가 잡히지 않았다… 정말 삽질을 많이 했다.. 결국 not blank 말고, 새로운 custom annotation을 만들어볼까도 생각했을 정도…

그것밖엔 정말 없는 걸까..간단한 방법이 있을텐데..하면서 계속 삽질한 결과!!!!

인텔리제이 application 실행 log에서 해답을 얻었다!!!!!!!

  • application.log
2024-01-06T21:14:27.362+09:00  WARN 23636 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'major' for method parameter type String is not present]

바로 어디서 Exception이 되고 있는지 알려주던 것이다!

DefaultHandlerExceptionResolver에서 MissingServletRequestParameterException을 잡았고,

그게 “Required request parameter 'major' for method parameter type String is not present” 이러한 오류가 있다고 메세지를 보여준 것이었다!!!!!!!

그래서 나는 BaseExceptionHandler에서 MissingServletRequestParameterException를 잡아 return 값만 변경해주면 됐다!

  • BaseExceptionHandler
@RestControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(BaseException.class)
    protected BaseResponse handleBaseException(BaseException ex){
        return new BaseResponse(ex.getBaseResponseStatus());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    protected BaseResponse validException(MissingServletRequestParameterException ex){
        return new BaseResponse<>(BaseResponseStatus.REQUEST_BLANK);
    }
}
  • PortalController
@RequestMapping("/v1/api/portals")
@RestController
@RequiredArgsConstructor
public class PortalController {

    private final PortalService portalService;

    @GetMapping("/search")
    public BaseResponse<List<PortalResponseDto>> PortalSearch(@RequestParam("major") String major, @RequestParam("keyword") String keyword, @RequestParam("condition") Condition condition) {

        List<PortalResponseDto> res = null;

        if (condition.equals(Condition.name)) {
            res = portalService.searchByLectureName(major, keyword);
        } else if (condition.equals(Condition.professor)) {
            res = portalService.searchByProfessorName(major, keyword);
        }

        return new BaseResponse < List<PortalResponseDto>> (res);
    }
}
  • 결과
profile
멋진 개발자가 될테야

0개의 댓글