Best way to check for inner exception?

Viewed 97273

I know sometimes innerException is null

So the following might fail:

 repEvent.InnerException = ex.InnerException.Message; 

Is there a quick ternary way to check if innerException is null or not?

15 Answers

You may simply write like this:

repEvent.InnerException = ex.InnerException?.Message ?? string.Empty;

For get other type of error you may write like this:

string exception = $"\n{nameof(AccountViewModel)}.{nameof(AccountCommand)}. \nMessage: {ex.Message}. \nInnerException:{ex.InnerException}. \nStackTrace: {ex.StackTrace}";

It is possible to use an exception filter to get more precise aiming.

catch (Exception ex) when (ex.InnerException != null) {...}

Please find more details here

Related