zoukankan      html  css  js  c++  java
  • 重写定义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

  • 相关阅读:
    WPF 实现窗体拖动
    CAP带你轻松玩转ASP.NETCore消息队列
    ASP.NET Core开发-获取所有注入(DI)服务
    k8s实战为aspnetcore.webapi微服务注入配置信息
    详解docker实战之搭建私有镜像仓库
    自己动手破解Z.EntityFramework.Extensions 4.0.11.0的方法
    可以获取随机图片的API收集 必应 等
    一键发布部署vs插件[AntDeploy],让net开发者更幸福
    比ngx_http_substitutions_filter_module 更强大的替换模块sregex的replace-filter-nginx-module
    编译nginx的源码安装subs_filter模块
  • 原文地址:https://www.cnblogs.com/javalinux/p/14365203.html
Copyright © 2011-2022 走看看