重寫定義Spring Boot FeignClient 捕獲異常信息


FeignClient 默認的解析器:

public static FeignException errorStatus(String methodKey, Response response) {
// 這里做了處理
String message = format("status %s reading %s", response.status(), methodKey);
try {
if (response.body() != null) {
String body = Util.toString(response.body().asReader());
message += "; content:\n" + body;
}
} catch (IOException ignored) { // NOPMD
}
return new FeignException(response.status(), message);
}
默認截獲的異常如下:

{
"timestamp": "2019-02-24 17:15:19",
"status": 500,
"error": "Internal Server Error",
"message": "status 400 reading PaymentInterface#methodName(ParamType,ParamType)
content: {"type":"http://httpstatus.es/404","title":"未找到資源","status":400,"detail":"這里是詳細的異常信息"} ",
"path": "/oauth/token"
}
自定義解析器:

@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

@Override
public Exception decode(String methodKey, Response response) {
try {
// 這里直接拿到我們拋出的異常信息
String message = Util.toString(response.body().asReader());
try {
JSONObject jsonObject = new JSONObject(message);
return new BaseException(jsonObject.getString("message"),jsonObject.getInt("status"));
} catch (JSONException e) {
e.printStackTrace();
}

} catch (IOException ignored) {
}
return decode(methodKey, response);
}
}
其中 BaseException類如:

public class BaseException extends RuntimeException {
private int status ;

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public BaseException() {
}

public BaseException(String message, int status) {
super(message);
this.status = status;
}

public BaseException(String message) {
super(message);
}

public BaseException(String message, Throwable cause) {
super(message, cause);
}

public BaseException(Throwable cause) {
super(cause);
}

public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
異常格式:

{
"timestamp": "2019-02-24 17:15:19",
"status": 500,
"error": "Internal Server Error",
"message": "用戶不存在",
"path": "/oauth/token"
}


轉載於:https://blog.51cto.com/4925054/2354156

 


免責聲明!

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



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