@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

评论已关闭。

站点统计

  • 文章总数:315 篇
  • 分类总数:20 个
  • 标签总数:193 个
  • 运行天数:1156 天
  • 访问总数:40040 人次

浙公网安备33011302000604

辽ICP备20003309号