Recording error messages from an exceptionerror handling logic in phpFunctional exception handling with TryCatchFinally statement helpersError Handling When Using DictionaryMaking error messages more efficientMap error messages to conditionsRead sales transactions from ExcelTwo similar methods to process a queue of messagesRetrieving all institutions in a specified countryURL decode a string but log an error after second exceptionVisual Studio exception visualizer for lengthy exception messages

Size of subfigure fitting its content (tikzpicture)

Saudi Arabia Transit Visa

How can I determine if the org that I'm currently connected to is a scratch org?

How did the Super Star Destroyer Executor get destroyed exactly?

Is it inappropriate for a student to attend their mentor's dissertation defense?

Arrow those variables!

Can we compute the area of a quadrilateral with one right angle when we only know the lengths of any three sides?

Detention in 1997

What exploit are these user agents trying to use?

Do UK voters know if their MP will be the Speaker of the House?

Unlock My Phone! February 2018

Examples of smooth manifolds admitting inbetween one and a continuum of complex structures

ssTTsSTtRrriinInnnnNNNIiinngg

What do you call someone who asks many questions?

Why are the 737's rear doors unusable in a water landing?

Gatling : Performance testing tool

Why no variance term in Bayesian logistic regression?

Why is this clock signal connected to a capacitor to gnd?

Is it logically or scientifically possible to artificially send energy to the body?

Why would the Red Woman birth a shadow if she worshipped the Lord of the Light?

Watching something be piped to a file live with tail

How does a predictive coding aid in lossless compression?

What is the most common color to indicate the input-field is disabled?

How do I handle a potential work/personal life conflict as the manager of one of my friends?



Recording error messages from an exception


error handling logic in phpFunctional exception handling with TryCatchFinally statement helpersError Handling When Using DictionaryMaking error messages more efficientMap error messages to conditionsRead sales transactions from ExcelTwo similar methods to process a queue of messagesRetrieving all institutions in a specified countryURL decode a string but log an error after second exceptionVisual Studio exception visualizer for lengthy exception messages













4












$begingroup$


How do I shorten these if else statements? As you can see, those elses are repeated.



if (exception.InnerException != null)

if (!string.IsNullOrEmpty(exception.InnerException.Message))

errorMessage = exception.InnerException.Message;

else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();


else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();










share|improve this question











$endgroup$











  • $begingroup$
    If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string.
    $endgroup$
    – jrh
    Jan 2 '18 at 12:49






  • 1




    $begingroup$
    Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string.
    $endgroup$
    – AsheraH
    Jan 2 '18 at 13:51















4












$begingroup$


How do I shorten these if else statements? As you can see, those elses are repeated.



if (exception.InnerException != null)

if (!string.IsNullOrEmpty(exception.InnerException.Message))

errorMessage = exception.InnerException.Message;

else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();


else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();










share|improve this question











$endgroup$











  • $begingroup$
    If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string.
    $endgroup$
    – jrh
    Jan 2 '18 at 12:49






  • 1




    $begingroup$
    Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string.
    $endgroup$
    – AsheraH
    Jan 2 '18 at 13:51













4












4








4





$begingroup$


How do I shorten these if else statements? As you can see, those elses are repeated.



if (exception.InnerException != null)

if (!string.IsNullOrEmpty(exception.InnerException.Message))

errorMessage = exception.InnerException.Message;

else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();


else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();










share|improve this question











$endgroup$




How do I shorten these if else statements? As you can see, those elses are repeated.



if (exception.InnerException != null)

if (!string.IsNullOrEmpty(exception.InnerException.Message))

errorMessage = exception.InnerException.Message;

else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();


else if (!string.IsNullOrEmpty(exception.Message))

errorMessage = exception.Message;

else

errorMessage = exception.ToString();







c# error-handling asp.net-mvc-4






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 '18 at 4:31









Jamal

30.6k11121227




30.6k11121227










asked Jan 2 '18 at 4:08









PopPop

142210




142210











  • $begingroup$
    If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string.
    $endgroup$
    – jrh
    Jan 2 '18 at 12:49






  • 1




    $begingroup$
    Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string.
    $endgroup$
    – AsheraH
    Jan 2 '18 at 13:51
















  • $begingroup$
    If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string.
    $endgroup$
    – jrh
    Jan 2 '18 at 12:49






  • 1




    $begingroup$
    Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string.
    $endgroup$
    – AsheraH
    Jan 2 '18 at 13:51















$begingroup$
If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string.
$endgroup$
– jrh
Jan 2 '18 at 12:49




$begingroup$
If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string.
$endgroup$
– jrh
Jan 2 '18 at 12:49




1




1




$begingroup$
Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string.
$endgroup$
– AsheraH
Jan 2 '18 at 13:51




$begingroup$
Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string.
$endgroup$
– AsheraH
Jan 2 '18 at 13:51










3 Answers
3






active

oldest

votes


















8












$begingroup$

In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):



ver errorMessage = exception.InnerException?.Message ?? 
exception.Message ??
exception.ToString();


Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...



If you fear that situation, you can always create an extension method for strings that will return null for empty strings:



public static string NullIfEmpty(this string str)

return string.IsNullOrEmpty(str) ? null : str;



and then use it like this:



ver errorMessage = exception.InnerException?.Message?.NullIfEmpty() ?? 
exception.Message?.NullIfEmpty() ??
exception.ToString();





share|improve this answer











$endgroup$












  • $begingroup$
    it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
    $endgroup$
    – zaitsman
    Jan 2 '18 at 11:22











  • $begingroup$
    @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
    $endgroup$
    – Zohar Peled
    Jan 2 '18 at 11:36


















6












$begingroup$

Assuming you have at least c# 6 (and thus, the null propagation operator), you can simplify it like this:



 if (!string.IsNullOrEmpty(exception?.InnerException?.Message))

errorMessage = exception.InnerException.Message;

else if (!string.IsNullOrEmpty(exception?.Message))

errorMessage = exception.Message;

else

errorMessage = exception?.ToString();



This will handle anything being null along the way.






share|improve this answer











$endgroup$




















    3












    $begingroup$

    You can use GetBaseException to get the lowest level exception.



    var message = exception.GetBaseException()?.Message;
    if(string.IsNullOrEmpty(message))
    message = exception.ToString();





    share|improve this answer









    $endgroup$













      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',
      autoActivateHeartbeat: false,
      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%2f184071%2frecording-error-messages-from-an-exception%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      8












      $begingroup$

      In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):



      ver errorMessage = exception.InnerException?.Message ?? 
      exception.Message ??
      exception.ToString();


      Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...



      If you fear that situation, you can always create an extension method for strings that will return null for empty strings:



      public static string NullIfEmpty(this string str)

      return string.IsNullOrEmpty(str) ? null : str;



      and then use it like this:



      ver errorMessage = exception.InnerException?.Message?.NullIfEmpty() ?? 
      exception.Message?.NullIfEmpty() ??
      exception.ToString();





      share|improve this answer











      $endgroup$












      • $begingroup$
        it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
        $endgroup$
        – zaitsman
        Jan 2 '18 at 11:22











      • $begingroup$
        @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
        $endgroup$
        – Zohar Peled
        Jan 2 '18 at 11:36















      8












      $begingroup$

      In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):



      ver errorMessage = exception.InnerException?.Message ?? 
      exception.Message ??
      exception.ToString();


      Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...



      If you fear that situation, you can always create an extension method for strings that will return null for empty strings:



      public static string NullIfEmpty(this string str)

      return string.IsNullOrEmpty(str) ? null : str;



      and then use it like this:



      ver errorMessage = exception.InnerException?.Message?.NullIfEmpty() ?? 
      exception.Message?.NullIfEmpty() ??
      exception.ToString();





      share|improve this answer











      $endgroup$












      • $begingroup$
        it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
        $endgroup$
        – zaitsman
        Jan 2 '18 at 11:22











      • $begingroup$
        @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
        $endgroup$
        – Zohar Peled
        Jan 2 '18 at 11:36













      8












      8








      8





      $begingroup$

      In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):



      ver errorMessage = exception.InnerException?.Message ?? 
      exception.Message ??
      exception.ToString();


      Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...



      If you fear that situation, you can always create an extension method for strings that will return null for empty strings:



      public static string NullIfEmpty(this string str)

      return string.IsNullOrEmpty(str) ? null : str;



      and then use it like this:



      ver errorMessage = exception.InnerException?.Message?.NullIfEmpty() ?? 
      exception.Message?.NullIfEmpty() ??
      exception.ToString();





      share|improve this answer











      $endgroup$



      In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):



      ver errorMessage = exception.InnerException?.Message ?? 
      exception.Message ??
      exception.ToString();


      Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...



      If you fear that situation, you can always create an extension method for strings that will return null for empty strings:



      public static string NullIfEmpty(this string str)

      return string.IsNullOrEmpty(str) ? null : str;



      and then use it like this:



      ver errorMessage = exception.InnerException?.Message?.NullIfEmpty() ?? 
      exception.Message?.NullIfEmpty() ??
      exception.ToString();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 1 min ago

























      answered Jan 2 '18 at 8:28









      Zohar PeledZohar Peled

      1814




      1814











      • $begingroup$
        it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
        $endgroup$
        – zaitsman
        Jan 2 '18 at 11:22











      • $begingroup$
        @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
        $endgroup$
        – Zohar Peled
        Jan 2 '18 at 11:36
















      • $begingroup$
        it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
        $endgroup$
        – zaitsman
        Jan 2 '18 at 11:22











      • $begingroup$
        @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
        $endgroup$
        – Zohar Peled
        Jan 2 '18 at 11:36















      $begingroup$
      it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
      $endgroup$
      – zaitsman
      Jan 2 '18 at 11:22





      $begingroup$
      it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though.
      $endgroup$
      – zaitsman
      Jan 2 '18 at 11:22













      $begingroup$
      @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
      $endgroup$
      – Zohar Peled
      Jan 2 '18 at 11:36




      $begingroup$
      @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message.
      $endgroup$
      – Zohar Peled
      Jan 2 '18 at 11:36













      6












      $begingroup$

      Assuming you have at least c# 6 (and thus, the null propagation operator), you can simplify it like this:



       if (!string.IsNullOrEmpty(exception?.InnerException?.Message))

      errorMessage = exception.InnerException.Message;

      else if (!string.IsNullOrEmpty(exception?.Message))

      errorMessage = exception.Message;

      else

      errorMessage = exception?.ToString();



      This will handle anything being null along the way.






      share|improve this answer











      $endgroup$

















        6












        $begingroup$

        Assuming you have at least c# 6 (and thus, the null propagation operator), you can simplify it like this:



         if (!string.IsNullOrEmpty(exception?.InnerException?.Message))

        errorMessage = exception.InnerException.Message;

        else if (!string.IsNullOrEmpty(exception?.Message))

        errorMessage = exception.Message;

        else

        errorMessage = exception?.ToString();



        This will handle anything being null along the way.






        share|improve this answer











        $endgroup$















          6












          6








          6





          $begingroup$

          Assuming you have at least c# 6 (and thus, the null propagation operator), you can simplify it like this:



           if (!string.IsNullOrEmpty(exception?.InnerException?.Message))

          errorMessage = exception.InnerException.Message;

          else if (!string.IsNullOrEmpty(exception?.Message))

          errorMessage = exception.Message;

          else

          errorMessage = exception?.ToString();



          This will handle anything being null along the way.






          share|improve this answer











          $endgroup$



          Assuming you have at least c# 6 (and thus, the null propagation operator), you can simplify it like this:



           if (!string.IsNullOrEmpty(exception?.InnerException?.Message))

          errorMessage = exception.InnerException.Message;

          else if (!string.IsNullOrEmpty(exception?.Message))

          errorMessage = exception.Message;

          else

          errorMessage = exception?.ToString();



          This will handle anything being null along the way.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 2 '18 at 6:24









          Sᴀᴍ Onᴇᴌᴀ

          10.1k62167




          10.1k62167










          answered Jan 2 '18 at 4:15









          zaitsmanzaitsman

          16114




          16114





















              3












              $begingroup$

              You can use GetBaseException to get the lowest level exception.



              var message = exception.GetBaseException()?.Message;
              if(string.IsNullOrEmpty(message))
              message = exception.ToString();





              share|improve this answer









              $endgroup$

















                3












                $begingroup$

                You can use GetBaseException to get the lowest level exception.



                var message = exception.GetBaseException()?.Message;
                if(string.IsNullOrEmpty(message))
                message = exception.ToString();





                share|improve this answer









                $endgroup$















                  3












                  3








                  3





                  $begingroup$

                  You can use GetBaseException to get the lowest level exception.



                  var message = exception.GetBaseException()?.Message;
                  if(string.IsNullOrEmpty(message))
                  message = exception.ToString();





                  share|improve this answer









                  $endgroup$



                  You can use GetBaseException to get the lowest level exception.



                  var message = exception.GetBaseException()?.Message;
                  if(string.IsNullOrEmpty(message))
                  message = exception.ToString();






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 2 '18 at 12:29









                  Mike NorgateMike Norgate

                  1312




                  1312



























                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f184071%2frecording-error-messages-from-an-exception%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

                      कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

                      Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

                      चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि