Skip to content

Commit

Permalink
Merge pull request #38 from dev-hooon/feat/#36
Browse files Browse the repository at this point in the history
feat : CustomExceptionHandlerFilter를 통한 예외처리
  • Loading branch information
kkangh00n authored Jan 2, 2024
2 parents 9edf1a0 + 5ed28d1 commit 561e7b8
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
@RequiredArgsConstructor
public enum ErrorCode {
NOT_EXIST_MEMBER("존재하지 않는 회원입니다."),
NOT_FOUND_REFRESH_TOKEN("유효하지 않은 RefreshToken입니다."),
TOKEN_EXPIRES("토큰이 만료되었습니다. 다시 로그인 해 주세요."),

ALREADY_PREOCCUPIED_RESERVATION_TIME("이미 타인에게 선점권이 있는 예약시간입니다."),
ALREADY_OCCUPIED_RESERVATION_TIME("이미 예약된 시간입니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.prgrms.catchtable.jwt.filter;

import static com.prgrms.catchtable.common.exception.ErrorCode.TOKEN_EXPIRES;

import com.prgrms.catchtable.common.exception.custom.BadRequestCustomException;
import com.prgrms.catchtable.jwt.domain.RefreshToken;
import com.prgrms.catchtable.jwt.provider.JwtTokenProvider;
import com.prgrms.catchtable.jwt.service.RefreshTokenService;
Expand All @@ -15,7 +18,6 @@
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
Expand Down Expand Up @@ -50,7 +52,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
newToken.getAccessToken());
setAuthentication(newToken.getAccessToken());
} else {
throw new UsernameNotFoundException("Please Login again");
throw new BadRequestCustomException(TOKEN_EXPIRES);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.prgrms.catchtable.jwt.service;

import static com.prgrms.catchtable.common.exception.ErrorCode.NOT_EXIST_MEMBER;

import com.prgrms.catchtable.common.exception.custom.NotFoundCustomException;
import com.prgrms.catchtable.member.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -16,6 +19,6 @@ public class JwtUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return memberRepository.findMemberByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("Not Found Member"));
.orElseThrow(() -> new NotFoundCustomException(NOT_EXIST_MEMBER));
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.prgrms.catchtable.jwt.service;

import static com.prgrms.catchtable.common.exception.ErrorCode.NOT_FOUND_REFRESH_TOKEN;

import com.prgrms.catchtable.common.exception.custom.NotFoundCustomException;
import com.prgrms.catchtable.jwt.domain.RefreshToken;
import com.prgrms.catchtable.jwt.repository.RefreshTokenRepository;
import com.prgrms.catchtable.jwt.token.Token;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand Down Expand Up @@ -33,6 +35,6 @@ public void saveRefreshToken(Token totalToken) {
@Transactional(readOnly = true)
public RefreshToken getRefreshTokenByToken(String refreshToken) {
return refreshTokenRepository.findRefreshTokenByToken(refreshToken)
.orElseThrow(() -> new UsernameNotFoundException("Not Found RefreshToken"));
.orElseThrow(() -> new NotFoundCustomException(NOT_FOUND_REFRESH_TOKEN));
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.prgrms.catchtable.security.config;

import com.prgrms.catchtable.jwt.filter.JwtAuthenticationFilter;
import com.prgrms.catchtable.security.filter.ExceptionHandlerFilter;
import com.prgrms.catchtable.security.service.CustomOAuth2SuccessHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
Expand All @@ -19,7 +20,7 @@
public class SecurityConfig {

private final CustomOAuth2SuccessHandler successHandler;

private final ExceptionHandlerFilter exceptionHandlerFilter;
private final JwtAuthenticationFilter jwtAuthenticationFilter;

@Bean
Expand All @@ -35,6 +36,9 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
)
.oauth2Login(oauth2Login -> oauth2Login.successHandler(successHandler));

http.addFilterBefore(exceptionHandlerFilter,
OAuth2AuthorizationRequestRedirectFilter.class);

http.addFilterBefore(jwtAuthenticationFilter,
OAuth2AuthorizationRequestRedirectFilter.class);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.prgrms.catchtable.security.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.prgrms.catchtable.common.exception.ErrorResponse;
import com.prgrms.catchtable.common.exception.custom.BadRequestCustomException;
import com.prgrms.catchtable.common.exception.custom.NotFoundCustomException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.GenericFilter;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Component;

@Component
public class ExceptionHandlerFilter extends GenericFilter {

private final ObjectMapper mapper = new ObjectMapper();

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

HttpServletResponse httpServletResponse = (HttpServletResponse) response;

try {
chain.doFilter(request, response);
} catch (BadRequestCustomException be) {
httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
sendJson(httpServletResponse, toJson(new ErrorResponse(be.getErrorCode())));
} catch (NotFoundCustomException ne) {
httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
sendJson(httpServletResponse, toJson(new ErrorResponse(ne.getErrorCode())));
}
}

private String toJson(ErrorResponse response) throws JsonProcessingException {
return mapper.writeValueAsString(response);
}

private void sendJson(HttpServletResponse response, String resultJson) throws IOException {
response.setContentType("application/json;charset=UTF-8");
response.setContentLength(resultJson.getBytes().length);
response.getWriter().write(resultJson);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
@RequiredArgsConstructor
public class CustomOAuth2SuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

private final ObjectMapper objectMapper = new ObjectMapper();
private final MemberService memberService;

@Override
Expand All @@ -38,15 +39,13 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
}

public String tokenToJson(Token token) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(token);
}

private void sendTokenJson(HttpServletResponse response, String tokenJson) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json;charset=UTF-8");
response.setContentLength(tokenJson.getBytes().length);
response.getWriter().write(tokenJson);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
@AutoConfigureMockMvc
public abstract class BaseIntegrationTest {

public static ObjectMapper objectMapper = new ObjectMapper();
@Autowired
public MockMvc mockMvc;
public static ObjectMapper objectMapper = new ObjectMapper();

public static String asJsonString(final Object object) throws Exception {
return objectMapper.writeValueAsString(object);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,8 @@ class WaitingRepositoryTest {

@Autowired
private WaitingRepository waitingRepository;

@Autowired
private MemberRepository memberRepository;

@Autowired
private ShopRepository shopRepository;
private Shop shop;
Expand Down

0 comments on commit 561e7b8

Please sign in to comment.