TIL/Web Back

[Sparta] 내일배움캠프 TIL 28일차

헤르로우워르드 2024. 5. 30. 21:03
숙련주차 개인과제

 

spring 예외처리

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleNoSuchElementFoundException(IllegalArgumentException exception) {
        return ResponseEntity.status(400).body(exception.getMessage());
    }

 

위 Handler를 @Controller 단 안에 정의해둘경우..

 @PostMapping("/write")
    public CommentResponseDto createComment(@RequestBody @Valid CommentRequestDto requestDto, BindingResult bindingResult
    ,@CookieValue(JwtUtil.AUTHORIZATION_HEADER) String tokenValue) {

        checkError(bindingResult);
        if(!requestDto.getUsername().equals(getJwt(tokenValue))) {
            throw new IllegalArgumentException("잘못된 username");
        }
        return commentService.createComment(requestDto);
    }

위 api 요청시 오류났을때 예외처리 핸들링 세팅대로 반환됨 상태코드 400, body는 "잘못된 username" 문자열 들어감