@Slf4j
public class CustomDecoder implements Decoder {

    private static final String SUCCESS_CODE = "200";

    // 这里用作分发,是decode成成功请求,还是失败请求
    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        if (response.status() != 200) {
            return handleErrorResponse(response);
        } else {
            return handleSuccessResponse(response, type);
        }

    }

    private Object handleSuccessResponse(Response response, Type type) throws IOException {
        String body = Util.toString(response.body().asReader());
        log.info("Response: {}", body);
        Result<String> result = JSONObject.parseObject(body, new TypeReference<Result<String>>() {
        });
        HvResult hvResult = JSON.parseObject(result.getData(), type);
        if (!SUCCESS_CODE.equals(hikvisionResult.getCode())) {
            throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), hvResult.getMsg());
        }
        return hvResult;
    }

    private Object handleErrorResponse(Response response) throws IOException {
        String body = Util.toString(response.body().asReader());
        log.error("Response: {}", body);
        Result<Result> result = JSONObject.parseObject(body, new TypeReference<Result<Result>>() {
        });
        throw new CustomException(response.status(), result.getMsg());
    }

    public class CustomException extends RuntimeException {

        private final int status;

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

        public int getStatus() {
            return status;
        }

    }

1 条评论

gify · 2023-07-19 21:49

nice

发表评论

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注

站点统计

  • 文章总数:304 篇
  • 分类总数:19 个
  • 标签总数:189 个
  • 运行天数:864 天
  • 访问总数:475045 人次
ICP备案号: 辽ICP备20003309号