Feign 自定義 ErrorDecoder (捕獲 Feign 服務端異常)


問題描述

Feign 客戶端捕獲不到服務端拋出的異常

問題解決

重新 ErrorDecoder 即可,比如下面例子中在登錄鑒權時想使用認證服務器拋出 OAuth2Exception 的異常,代碼如下:

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

import java.io.IOException;

@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String message = Util.toString(response.body().asReader());

            ObjectMapper objectMapper = new ObjectMapper();
            OAuth2Exception oAuth2Exception = objectMapper.readValue(message, OAuth2Exception.class);
            return oAuth2Exception;
        } catch (IOException ignored) {
        }

        return decode(methodKey, response);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM