Skip to content

Commit

Permalink
[foundation] Enable nullable for MonoTouchException
Browse files Browse the repository at this point in the history
and avoid potential `NullReferenceException` in some code paths.

Also remove multiple string concatenations by using `StringBuilder`
  • Loading branch information
spouliot committed Aug 5, 2021
1 parent fa5f323 commit b48821b
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions src/Foundation/MonoTouchException.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
#if !MONOMAC

using System;
using System.Text;

#nullable enable

namespace Foundation {
public class MonoTouchException : Exception {
private NSException native_exc;
NSException? native_exc;

public MonoTouchException () : base () {
native_exc = new NSException ("default", String.Empty, null);
Expand All @@ -14,49 +17,51 @@ public MonoTouchException (NSException exc) : base () {
native_exc = exc;
}

public NSException NSException {
public NSException? NSException {
get {
return native_exc;
}
}

public string Reason {
public string? Reason {
get {
return native_exc.Reason;
return native_exc?.Reason;
}
}

public string Name {
public string? Name {
get {
return native_exc.Name;
return native_exc?.Name;
}
}

public override string Message {
get {
return string.Format ("Objective-C exception thrown. Name: {0} Reason: {1}\nNative stack trace:\n{2}", Name, Reason, NativeStackTrace);
var sb = new StringBuilder ("Objective-C exception thrown. Name: ").Append (Name);
sb.Append (" Reason: ").AppendLine (Reason);
sb.AppendLine ("Native stack trace:");
AppendNativeStackTrace (sb);
return sb.ToString ();
}
}

string NativeStackTrace {
get {
var symbols = native_exc.CallStackSymbols;
var msg = string.Empty;
for (int i = 0; i < symbols.Length; i++) {
msg += "\t" + symbols [i] + "\n";
}
return msg;
void AppendNativeStackTrace (StringBuilder sb)
{
if (native_exc is not null) {
foreach (var symbol in native_exc.CallStackSymbols)
sb.Append ('\t').AppendLine (symbol);
}
}

public override string ToString ()
{
var msg = base.ToString ();
if (native_exc is null)
return msg;

if (native_exc != null)
msg += NativeStackTrace;

return msg;
var sb = new StringBuilder (msg);
AppendNativeStackTrace (sb);
return sb.ToString ();
}
}
}
Expand Down

0 comments on commit b48821b

Please sign in to comment.