[MSA] FeignClient ์์ธ์ฒ๋ฆฌ : ErrorDecoder
Categories: MSA
Tags: MSA, SpringCloud
๐ ๊ฐ์ธ์ ์ธ ๊ณต๊ฐ์ผ๋ก ๊ณต๋ถ๋ฅผ ๊ธฐ๋กํ๊ณ ๋ณต์ตํ๊ธฐ ์ํด ์ฌ์ฉํ๋ ๋ธ๋ก๊ทธ์
๋๋ค.
์ ํํ์ง ์์ ์ ๋ณด๊ฐ ์์ ์ ์์ผ๋ ์ฐธ๊ณ ๋ฐ๋๋๋ค :๐ธ
[ํ๋ฆฐ ๋ด์ฉ์ ๋๊ธ๋ก ๋จ๊ฒจ์ฃผ์๋ฉด ๋ณต๋ฐ์ผ์ค๊ฑฐ์์]
์ธํ๋ฐ Dowon Lee๋์ Spring Cloud๋ก ๊ฐ๋ฐํ๋ ๋ง์ดํฌ๋ก์๋น์ค ์ ํ๋ฆฌ์ผ์ด์
(MSA) ๊ฐ์๋ฅผ ๋ฃ๊ณ ์ ๋ฆฌํ ๋ด์ฉ์
๋๋ค.๐
Spring Cloud๋ก ๊ฐ๋ฐํ๋ ๋ง์ดํฌ๋ก์๋น์ค ์ ํ๋ฆฌ์ผ์ด์
(MSA) ๊ฐ์ ๋ค์ผ๋ฌ ๊ฐ๊ธฐ๐ฉโ๐ซ
FeignClient ์์ธ์ฒ๋ฆฌ : ErrorDecoder
์ด๋ฒ์๋ Feing ํจํค์ง์์ ์ ๊ณตํด์ฃผ๋ ErrorDecoder ๋ผ๋ ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ์ฌeign Client์์ ๋ฐ์ํ๋ ์๋ฌ๋ฅผ ํจ์จ์ ์ผ๋ก ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํ๋ค.
ErrorDecoder
ErrorDecoder ์ธํฐํ์ด์ค๋ FeignClient ํธ์ถ ์ ๋ฐ์ํ ์๋ฌ๋ฅผ ์ํ ์ฝ๋๋ณ๋ก ๊ตฌ๋ถํด ์ฒ๋ฆฌํ ์ ์๋๋ก ์ง์ํ๋ค.
์ด๋ฅผ ํตํด ๋ ์ธ๋ถ์ ์ด๊ณ ์ฒด๊ณ์ ์ธ ์์ธ ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํ๋ฉฐ, ์ํ ์ฝ๋์ ๋ฐ๋ผ ์ปค์คํ ์์ธ๋ฅผ ๋์ง ์ ์๋ค.
decode
๋ฉ์๋๋ฅผ ๊ตฌํํ๋ฉด FeignClient ํธ์ถ ์ ๋ฐ์ํ ์ค๋ฅ์ ๋ํด ์ํ ์ฝ๋๋ณ๋ก ์ปค์คํ ๋ก์ง์ ์์ฑํ ์ ์๋ค.
ErrorDecoder๋ฅผ ์์๋ฐ๋ ํด๋์ค ์์ฑ
๋จผ์ , ErrorDecoder๋ฅผ ์์๋ฐ๋ ํด๋์ค๋ฅผ ์์ฑํ๊ณ ์ํ ์ฝ๋๋ณ๋ก ๋ก์ง์ ์์ฑํ๋ค.
- ๋งค๊ฐ๋ณ์๋ก response ์์ ํฌํจ๋์ด์๋ status ๊ฐ์ผ๋ก ํ๋จ
- switch case ๋ฌธ์์ ํตํด 400, 500, 404 ์ค๋ฅ์ ๋ํด์ ์ฒดํฌ
- 404 ์ค๋ฅ์์ getOrders ๋ฉ์๋์์ ๋ฐ์ํ๋ ์๋ฌ๋ผ๋ฉด ๊ทธ๋ฅ ๋ฉ์ธ์ง๋ฅผ ์ถ๋ ฅํด์ ์ฌ์ฉ์๊ฐ ์์ฒญํ๋ ์ฃผ๋ฌธ์ด ์๋ค๊ณ ํ์๋ฅผ ๋ํ๋ผ ์ ์๋ค.
- ๋๋ค ์๋๋ผ๊ณ ํ๋ฉด default ๋ฌธ์ผ๋ก ์์ธ ๊ฐ์ฒด๋ฅผ ๋ฐํ
Application ํด๋์ค์ ErrorDecoder ๋น ๋ฑ๋ก
๋น์ผ๋ก ๋ฑ๋กํด์ผ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ application class ์ ๋น์ผ๋ก ๋ฑ๋ก ํ ์ ์๋ค.
๊ธฐ์กด UserServiceImpl ์ฝ๋ ์์
-
์ง๋๋ฒ ์์ธ์ฒ๋ฆฌ๋ฅผ ์ํด try~catch ๋ฌธ์ผ๋ก ๋ณ๊ฒฝํ๋ ์ฝ๋๋ฅผ ์ฃผ์์ฒ๋ฆฌ
-
ErrorDecoder๋ฅผ ์ด์ฉํด์ error handling ํ๋ ์ฝ๋๋ก ์์
1 2 3 4 5
/* ErrorDecoder */ List<ResponseOrder> ordersList = orderServiceClient.getOrders(userId); userDto.setOrders(ordersList); return userDto;
-
Test
์ค์ ํ์ผ์ ๋ฑ๋กํ์ฌ ๊ตฌํํ๋ ๋ฐฉ๋ฒ
-
user-service.yml์์ ์์ธ ๋ฑ๋ก
1 2 3 4
order_service: url: http://ORDER-SERVICE/order-service/%s/orders exception: order_is_empty: User's orders is empty
-
FeignErrorDecoder ์ ์์ฑ์ ์ฃผ์ ๋ฐ @Component ๋ฑ๋ก
ErrorDecoder์์ ํ๊ฒฝ ๋ณ์๋ฅผ ์ฃผ์ ๋ฐ์ ๋ฉ์์ง๋ฅผ ๋์ ์ผ๋ก ์ค์ ํ๋ค
1 2 3 4 5 6 7 8 9
@Component public class FeignErrorDecoder implements ErrorDecoder { Environment env; @Autowired public FeignErrorDecoder(Environment env) { this.env = env; }
-
Component ๋ก ๋ฑ๋กํ๊ธฐ ๋๋ฌธ์ Application ํด๋์ค์ ๋น์ ์ ๊ฑฐํด์ผ ํ๋ค.
์ผ๋ฐ์ ์ธ try-catch์ ErrorDecoder์ ์ฐจ์ด์
- try-catch ๋ฐฉ์
- ๊ฐ๋จํ ์์ธ ์ฒ๋ฆฌ์๋ ์ ํฉํ๋, ์ฝ๋๊ฐ ๋ณต์กํด์ง๊ณ ๋ฐ๋ณต์ ์ด๊ธฐ ์ฌ์.
- ๋ชจ๋ Feign ํธ์ถ์ try-catch๋ฅผ ์ถ๊ฐํด์ผ ํ๋ ๋นํจ์จ์ด ๋ฐ์.
- ErrorDecoder ๋ฐฉ์
- ์ํ ์ฝ๋์ ๋ฐ๋ผ ์ค์ ์ง์ค์์ผ๋ก ์์ธ ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅ.
- ์ํ ์ฝ๋ ๊ธฐ๋ฐ ์ปค์คํ ์์ธ ์์ฑ์ด ๊ฐ๋ฅ.
- Feign๊ณผ ์์ฐ์ค๋ฝ๊ฒ ํตํฉ๋๋ฉฐ ์ ์ง๋ณด์๊ฐ ๊ฐํธ.
๐ ์ ๋ฆฌ
ErrorDecoder๋ Feign Client ํธ์ถ ์ ๋ฐ์ํ๋ ๋ค์ํ ์๋ฌ๋ฅผ ์ฒด๊ณ์ ์ผ๋ก ์ฒ๋ฆฌํ๋ ๋ฐ ์ ์ฉํ๋ค.
try-catch์ ๋นํด ์ฝ๋๊ฐ ๊ฐ๊ฒฐํ๋ฉฐ, ์ํ ์ฝ๋๋ณ๋ก ์ธ๋ถํ๋ ๋ก์ง์ ์ ์ฉํ ์ ์์ด ์ถ์ฒํ๋ ๋ฐฉ์์ด๋ค.
๋ํ, ์ค์ ํ์ผ์ ํตํด ๋ฉ์์ง๋ฅผ ๊ด๋ฆฌํ๋ฉด ํ๊ฒฝ ๋ณํ์๋ ์ ์ฐํ๊ฒ ๋์ํ ์ ์๋ค.
Leave a comment