How to return error message from rest service





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I have defined a rest service with Spring boot which returns an interface. When it occurs an error in the service, how can I return a meaningful error message ? On browser, as a result, I display Json of MyInterface type.



The code below is the service called by the controller:



public MyInterface getSomeTask() {

// business logic here
MyInterface myObject= getRelatedClass();

if(myObject == null){
// how to return error message
}

return myObject;
}









share|improve this question































    1















    I have defined a rest service with Spring boot which returns an interface. When it occurs an error in the service, how can I return a meaningful error message ? On browser, as a result, I display Json of MyInterface type.



    The code below is the service called by the controller:



    public MyInterface getSomeTask() {

    // business logic here
    MyInterface myObject= getRelatedClass();

    if(myObject == null){
    // how to return error message
    }

    return myObject;
    }









    share|improve this question



























      1












      1








      1








      I have defined a rest service with Spring boot which returns an interface. When it occurs an error in the service, how can I return a meaningful error message ? On browser, as a result, I display Json of MyInterface type.



      The code below is the service called by the controller:



      public MyInterface getSomeTask() {

      // business logic here
      MyInterface myObject= getRelatedClass();

      if(myObject == null){
      // how to return error message
      }

      return myObject;
      }









      share|improve this question
















      I have defined a rest service with Spring boot which returns an interface. When it occurs an error in the service, how can I return a meaningful error message ? On browser, as a result, I display Json of MyInterface type.



      The code below is the service called by the controller:



      public MyInterface getSomeTask() {

      // business logic here
      MyInterface myObject= getRelatedClass();

      if(myObject == null){
      // how to return error message
      }

      return myObject;
      }






      spring rest spring-mvc spring-rest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 8:59









      veben

      2,24851629




      2,24851629










      asked Nov 22 '18 at 8:36









      user1474111user1474111

      2501323




      2501323
























          1 Answer
          1






          active

          oldest

          votes


















          0














          One of the possibilities would be to throw Exception and then handle it with Spring so it would return proper json.



          You may want to look at this article about error handling.



          You coud create custom exception that will be throwed inside your logic and then handle it:



          if(myObject == null){
          throw new CouldNotGetRelatedClassException();
          }


          and in controller you may use error handling method like:



          public class FooController {

          @ExceptionHandler({ CouldNotGetRelatedClassException.class})
          public void handleException() {
          // logic of exception handling
          }

          }


          Another way may be creating class with @ControllerAdvice annotation that will create custom json response on throwed exceptions:



          @ControllerAdvice
          public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

          @ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
          protected ResponseEntity<Object> handleNotFound(
          RuntimeException ex, WebRequest request) {
          String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse,
          new HttpHeaders(), HttpStatus.NOT_FOUND, request);
          }
          }


          However you may want to be aware that error responses may have different structure that your normal object so you may want to return it with different HTTP status code so frontend could determine that this message will be deserialized differently.






          share|improve this answer





















          • 1





            thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

            – user1474111
            Nov 22 '18 at 9:22






          • 1





            @user1474111 I have added more examples

            – Tomasz Bawor
            Nov 22 '18 at 9:31












          Your Answer






          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: "1"
          };
          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',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          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%2fstackoverflow.com%2fquestions%2f53426803%2fhow-to-return-error-message-from-rest-service%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









          0














          One of the possibilities would be to throw Exception and then handle it with Spring so it would return proper json.



          You may want to look at this article about error handling.



          You coud create custom exception that will be throwed inside your logic and then handle it:



          if(myObject == null){
          throw new CouldNotGetRelatedClassException();
          }


          and in controller you may use error handling method like:



          public class FooController {

          @ExceptionHandler({ CouldNotGetRelatedClassException.class})
          public void handleException() {
          // logic of exception handling
          }

          }


          Another way may be creating class with @ControllerAdvice annotation that will create custom json response on throwed exceptions:



          @ControllerAdvice
          public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

          @ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
          protected ResponseEntity<Object> handleNotFound(
          RuntimeException ex, WebRequest request) {
          String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse,
          new HttpHeaders(), HttpStatus.NOT_FOUND, request);
          }
          }


          However you may want to be aware that error responses may have different structure that your normal object so you may want to return it with different HTTP status code so frontend could determine that this message will be deserialized differently.






          share|improve this answer





















          • 1





            thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

            – user1474111
            Nov 22 '18 at 9:22






          • 1





            @user1474111 I have added more examples

            – Tomasz Bawor
            Nov 22 '18 at 9:31
















          0














          One of the possibilities would be to throw Exception and then handle it with Spring so it would return proper json.



          You may want to look at this article about error handling.



          You coud create custom exception that will be throwed inside your logic and then handle it:



          if(myObject == null){
          throw new CouldNotGetRelatedClassException();
          }


          and in controller you may use error handling method like:



          public class FooController {

          @ExceptionHandler({ CouldNotGetRelatedClassException.class})
          public void handleException() {
          // logic of exception handling
          }

          }


          Another way may be creating class with @ControllerAdvice annotation that will create custom json response on throwed exceptions:



          @ControllerAdvice
          public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

          @ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
          protected ResponseEntity<Object> handleNotFound(
          RuntimeException ex, WebRequest request) {
          String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse,
          new HttpHeaders(), HttpStatus.NOT_FOUND, request);
          }
          }


          However you may want to be aware that error responses may have different structure that your normal object so you may want to return it with different HTTP status code so frontend could determine that this message will be deserialized differently.






          share|improve this answer





















          • 1





            thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

            – user1474111
            Nov 22 '18 at 9:22






          • 1





            @user1474111 I have added more examples

            – Tomasz Bawor
            Nov 22 '18 at 9:31














          0












          0








          0







          One of the possibilities would be to throw Exception and then handle it with Spring so it would return proper json.



          You may want to look at this article about error handling.



          You coud create custom exception that will be throwed inside your logic and then handle it:



          if(myObject == null){
          throw new CouldNotGetRelatedClassException();
          }


          and in controller you may use error handling method like:



          public class FooController {

          @ExceptionHandler({ CouldNotGetRelatedClassException.class})
          public void handleException() {
          // logic of exception handling
          }

          }


          Another way may be creating class with @ControllerAdvice annotation that will create custom json response on throwed exceptions:



          @ControllerAdvice
          public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

          @ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
          protected ResponseEntity<Object> handleNotFound(
          RuntimeException ex, WebRequest request) {
          String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse,
          new HttpHeaders(), HttpStatus.NOT_FOUND, request);
          }
          }


          However you may want to be aware that error responses may have different structure that your normal object so you may want to return it with different HTTP status code so frontend could determine that this message will be deserialized differently.






          share|improve this answer















          One of the possibilities would be to throw Exception and then handle it with Spring so it would return proper json.



          You may want to look at this article about error handling.



          You coud create custom exception that will be throwed inside your logic and then handle it:



          if(myObject == null){
          throw new CouldNotGetRelatedClassException();
          }


          and in controller you may use error handling method like:



          public class FooController {

          @ExceptionHandler({ CouldNotGetRelatedClassException.class})
          public void handleException() {
          // logic of exception handling
          }

          }


          Another way may be creating class with @ControllerAdvice annotation that will create custom json response on throwed exceptions:



          @ControllerAdvice
          public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

          @ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
          protected ResponseEntity<Object> handleNotFound(
          RuntimeException ex, WebRequest request) {
          String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse,
          new HttpHeaders(), HttpStatus.NOT_FOUND, request);
          }
          }


          However you may want to be aware that error responses may have different structure that your normal object so you may want to return it with different HTTP status code so frontend could determine that this message will be deserialized differently.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 '18 at 9:30

























          answered Nov 22 '18 at 9:02









          Tomasz BaworTomasz Bawor

          755627




          755627








          • 1





            thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

            – user1474111
            Nov 22 '18 at 9:22






          • 1





            @user1474111 I have added more examples

            – Tomasz Bawor
            Nov 22 '18 at 9:31














          • 1





            thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

            – user1474111
            Nov 22 '18 at 9:22






          • 1





            @user1474111 I have added more examples

            – Tomasz Bawor
            Nov 22 '18 at 9:31








          1




          1





          thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

          – user1474111
          Nov 22 '18 at 9:22





          thanks for the answer. But hadleException method does not return anything, so how browser will show any json on the screen?. Changing return type to MyInterface and creating new implementation for MyInterface to return when there is an exception might be an option. Is it the way how it should be or is it bad practice ?

          – user1474111
          Nov 22 '18 at 9:22




          1




          1





          @user1474111 I have added more examples

          – Tomasz Bawor
          Nov 22 '18 at 9:31





          @user1474111 I have added more examples

          – Tomasz Bawor
          Nov 22 '18 at 9:31




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • 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%2fstackoverflow.com%2fquestions%2f53426803%2fhow-to-return-error-message-from-rest-service%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

          Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

          ComboBox Display Member on multiple fields

          Is it possible to collect Nectar points via Trainline?