Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get stack trace error in Swift?

In Objective-C, Whenever an application crashes, I can get stack trace to see where is the last method that causes the error by using this code in AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     NSSetUncaughtExceptionHandler(&myExceptionHandler);
     return YES;
 }

void myExceptionHandler(NSException *exception)
{
    NSArray *stack = [exception callStackSymbols];
    NSLog(@"Stack trace: %@", stack);
    
    NSLog(@"MyExceptionHandler");
}

and it will print the stack trace log to console which I can use to debug the cause of the problem instead of ending up at main.m with no information

So how can I do this in Swift?

like image 808
SaintTail Avatar asked Jun 30 '14 09:06

SaintTail


People also ask

Does error contain stack trace?

The stack trace shows where the error occurs, namely in the c function. It also shows that the c function was called by b , which was called by a , which was in turn called by the code on line 15 (the last line) of the program.

How do I print a stack trace in Swift?

In Objective-C, you can print the call stack by doing the following: NSLog(@"%@", [NSThread callStackSymbols]);

What causes stack trace error?

What Triggered the Stack Trace? The thing that causes an Exception is usually an explicit throw statement. Using the file name and line number you can check exactly what code threw the Exception.


1 Answers

If I understand you correctly, I think what you are looking for is an exception breakpoint, which functions just like a regular breakpoint but is called whenever an exception is thrown. That way, it will stop your application right where the exception was thrown, so you can see the method, line of code, and variable values at the moment of the crash.

This can be set by going to the Breakpoint Navigator tab in the Navigator, clicking the plus at the bottom left and selecting "Add Exception Breakpoint ".

The Exception Breakpoint can than be edited with various options by right-clicking on it and selecting "Edit Breakpoint".

like image 181
dcgoss Avatar answered Nov 02 '22 11:11

dcgoss