Handling response from another microservice











up vote
0
down vote

favorite












I have this piece of code placed in ESI class. There is switch statement nested in a try-catch block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code.



@PostConstruct
public void initialize() {
this.webTarget = this.client.target("http://demo1173642.mockable.io/");
}

public Message getMockMessage() {
Response response = null;

try {
response = this.webTarget.request().get();

switch (response.getStatusInfo().getFamily()) {
case SUCCESSFUL:
return response.readEntity(Message.class);

case SERVER_ERROR:
throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
Response.Status.BAD_GATEWAY);

default:
throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
}

} catch (Exception ex) {
logger.log(Level.WARNING, ErrorCode.UNEXPECTED_EXECPTION.getMessage(), ex);
if (response != null) {
response.close();
}
throw new InternalServerErrorException();
}
}









share|improve this question


























    up vote
    0
    down vote

    favorite












    I have this piece of code placed in ESI class. There is switch statement nested in a try-catch block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code.



    @PostConstruct
    public void initialize() {
    this.webTarget = this.client.target("http://demo1173642.mockable.io/");
    }

    public Message getMockMessage() {
    Response response = null;

    try {
    response = this.webTarget.request().get();

    switch (response.getStatusInfo().getFamily()) {
    case SUCCESSFUL:
    return response.readEntity(Message.class);

    case SERVER_ERROR:
    throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
    Response.Status.BAD_GATEWAY);

    default:
    throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
    }

    } catch (Exception ex) {
    logger.log(Level.WARNING, ErrorCode.UNEXPECTED_EXECPTION.getMessage(), ex);
    if (response != null) {
    response.close();
    }
    throw new InternalServerErrorException();
    }
    }









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have this piece of code placed in ESI class. There is switch statement nested in a try-catch block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code.



      @PostConstruct
      public void initialize() {
      this.webTarget = this.client.target("http://demo1173642.mockable.io/");
      }

      public Message getMockMessage() {
      Response response = null;

      try {
      response = this.webTarget.request().get();

      switch (response.getStatusInfo().getFamily()) {
      case SUCCESSFUL:
      return response.readEntity(Message.class);

      case SERVER_ERROR:
      throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
      Response.Status.BAD_GATEWAY);

      default:
      throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
      }

      } catch (Exception ex) {
      logger.log(Level.WARNING, ErrorCode.UNEXPECTED_EXECPTION.getMessage(), ex);
      if (response != null) {
      response.close();
      }
      throw new InternalServerErrorException();
      }
      }









      share|improve this question













      I have this piece of code placed in ESI class. There is switch statement nested in a try-catch block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code.



      @PostConstruct
      public void initialize() {
      this.webTarget = this.client.target("http://demo1173642.mockable.io/");
      }

      public Message getMockMessage() {
      Response response = null;

      try {
      response = this.webTarget.request().get();

      switch (response.getStatusInfo().getFamily()) {
      case SUCCESSFUL:
      return response.readEntity(Message.class);

      case SERVER_ERROR:
      throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
      Response.Status.BAD_GATEWAY);

      default:
      throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
      }

      } catch (Exception ex) {
      logger.log(Level.WARNING, ErrorCode.UNEXPECTED_EXECPTION.getMessage(), ex);
      if (response != null) {
      response.close();
      }
      throw new InternalServerErrorException();
      }
      }






      java






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 26 at 10:55









      miki

      567




      567






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the exception case, but not in the success branch...



          Nevertheless, the throwing of a WebApplicationException leads me to believing that we are in a RESTful application here. Thus, the best way would be to declare an excepton mapper to handle the underlying ProcessingException (which is the only one your catch-all-block should encounter) and do not do the handling internally. For exception mappers, here's a tutorial to start with: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html (but you will find a lot more resources using your favourite search engine.)



          Having this out of the way, the only thing for your method to do is using a try-with-resources block for the response:



          public Message getMockMessage() {
          try(Response response = this.webTarget.request().get()) {
          switch (response.getStatusInfo().getFamily()) {
          case SUCCESSFUL:
          return response.readEntity(Message.class);
          case SERVER_ERROR:
          throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
          Response.Status.BAD_GATEWAY);
          default:
          throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
          }
          }





          share|improve this answer





















          • Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
            – miki
            Aug 27 at 7:37












          • Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
            – miki
            Aug 27 at 7:44











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f202509%2fhandling-response-from-another-microservice%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote













          In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the exception case, but not in the success branch...



          Nevertheless, the throwing of a WebApplicationException leads me to believing that we are in a RESTful application here. Thus, the best way would be to declare an excepton mapper to handle the underlying ProcessingException (which is the only one your catch-all-block should encounter) and do not do the handling internally. For exception mappers, here's a tutorial to start with: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html (but you will find a lot more resources using your favourite search engine.)



          Having this out of the way, the only thing for your method to do is using a try-with-resources block for the response:



          public Message getMockMessage() {
          try(Response response = this.webTarget.request().get()) {
          switch (response.getStatusInfo().getFamily()) {
          case SUCCESSFUL:
          return response.readEntity(Message.class);
          case SERVER_ERROR:
          throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
          Response.Status.BAD_GATEWAY);
          default:
          throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
          }
          }





          share|improve this answer





















          • Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
            – miki
            Aug 27 at 7:37












          • Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
            – miki
            Aug 27 at 7:44















          up vote
          0
          down vote













          In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the exception case, but not in the success branch...



          Nevertheless, the throwing of a WebApplicationException leads me to believing that we are in a RESTful application here. Thus, the best way would be to declare an excepton mapper to handle the underlying ProcessingException (which is the only one your catch-all-block should encounter) and do not do the handling internally. For exception mappers, here's a tutorial to start with: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html (but you will find a lot more resources using your favourite search engine.)



          Having this out of the way, the only thing for your method to do is using a try-with-resources block for the response:



          public Message getMockMessage() {
          try(Response response = this.webTarget.request().get()) {
          switch (response.getStatusInfo().getFamily()) {
          case SUCCESSFUL:
          return response.readEntity(Message.class);
          case SERVER_ERROR:
          throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
          Response.Status.BAD_GATEWAY);
          default:
          throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
          }
          }





          share|improve this answer





















          • Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
            – miki
            Aug 27 at 7:37












          • Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
            – miki
            Aug 27 at 7:44













          up vote
          0
          down vote










          up vote
          0
          down vote









          In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the exception case, but not in the success branch...



          Nevertheless, the throwing of a WebApplicationException leads me to believing that we are in a RESTful application here. Thus, the best way would be to declare an excepton mapper to handle the underlying ProcessingException (which is the only one your catch-all-block should encounter) and do not do the handling internally. For exception mappers, here's a tutorial to start with: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html (but you will find a lot more resources using your favourite search engine.)



          Having this out of the way, the only thing for your method to do is using a try-with-resources block for the response:



          public Message getMockMessage() {
          try(Response response = this.webTarget.request().get()) {
          switch (response.getStatusInfo().getFamily()) {
          case SUCCESSFUL:
          return response.readEntity(Message.class);
          case SERVER_ERROR:
          throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
          Response.Status.BAD_GATEWAY);
          default:
          throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
          }
          }





          share|improve this answer












          In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the exception case, but not in the success branch...



          Nevertheless, the throwing of a WebApplicationException leads me to believing that we are in a RESTful application here. Thus, the best way would be to declare an excepton mapper to handle the underlying ProcessingException (which is the only one your catch-all-block should encounter) and do not do the handling internally. For exception mappers, here's a tutorial to start with: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html (but you will find a lot more resources using your favourite search engine.)



          Having this out of the way, the only thing for your method to do is using a try-with-resources block for the response:



          public Message getMockMessage() {
          try(Response response = this.webTarget.request().get()) {
          switch (response.getStatusInfo().getFamily()) {
          case SUCCESSFUL:
          return response.readEntity(Message.class);
          case SERVER_ERROR:
          throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
          Response.Status.BAD_GATEWAY);
          default:
          throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 27 at 5:57









          mtj

          2,849213




          2,849213












          • Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
            – miki
            Aug 27 at 7:37












          • Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
            – miki
            Aug 27 at 7:44


















          • Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
            – miki
            Aug 27 at 7:37












          • Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
            – miki
            Aug 27 at 7:44
















          Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
          – miki
          Aug 27 at 7:37






          Thank you for your comprehensive response. Nevertheless, I'm afraid that you did not fully grasp the intention of the code. First of all - readEntity() closes stream after successful read, so closing it once again by hand is not required Second thing - yes, I do replace the exception but first I log the exception from the another microservice for debugging purposes. Exception outside this microservice has code 502 which propagates inside my system with 500 code. This behaviour I'd like to keep.
          – miki
          Aug 27 at 7:37














          Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
          – miki
          Aug 27 at 7:44




          Btw. read error messages represented by ErrorCode enum. Did you think that these are purposeless?
          – miki
          Aug 27 at 7:44


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f202509%2fhandling-response-from-another-microservice%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Сан-Квентин

          Алькесар

          Josef Freinademetz