0

How do I extract the exception from the error into the propery status? This doesn't work:

public class MyClass{ public string status { get; set; } public string MyAction() { try { ... status = "OK"; return status; } catch (Exception ex) { //throw ex; status = ex; } } } 
10
  • You can't assign Exception to a string... Did you mean to do status = ex.Message? Commented Aug 24, 2014 at 4:48
  • Don't you see...ex is a variable of type Exception, and status is a string? status = ex.ToString(); is what technically does what you're looking for, but I won't say this is a good exception handling design... Commented Aug 24, 2014 at 4:49
  • You should catch the specific types of exceptions happening, and create an enumeration for them so you could have properties like ErrorType and ErrorMessage. With ErrorType.Success being 0 in the enumeration. Or something like that. Using a string to drive a status in c# is a really bad design. Enumerations are much more reliable and easier to work with. Also, ToString on an enumeration will spit out the values name. And you can use Enum.Parse to parse a name into it's enumeration value. Commented Aug 24, 2014 at 4:59
  • @Ryios what if its a custom response from a WebException? Commented Aug 24, 2014 at 5:04
  • What are you trying to accomplish here? If you can't handle an exception, don't catch it. Commented Aug 24, 2014 at 5:26

2 Answers 2

1

Right now you're assigning the Exception object to the status variable. You need to use the actual message property of the Exception like so:

status = ex.Message; return status; 
Sign up to request clarification or add additional context in comments.

5 Comments

So you're saying all I have to do is change the current code in catch to what you have and it should all work?
I did, and it doesn't work. If I change it back to throw ex; it works, and returns the error.
It gives this error on MyAction() in the debugger: not all code paths return a value
Because your method isn't returning a value if you're just setting a variable. You should either return status after you give it a value, or return a generic error message.
Well really if all you're doing is returning status (bad idea in my opinion) then you don't even need the variable. You can just do return ex.Message;.
0

i think this will work

 public class MyClass { public string status { get; set; } public string MyAction() { try { return status = "OK"; } catch (Exception ex) { //throw ex; return status = ex.Message.ToString(); } } } 

2 Comments

Two problems. 1 - Not all exceptions have an inner exception. 2 - This will not return the message of either exception.
@logarr i just show the demo he can change that to message now is it clear

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.