Coding⏱️ 3 min read📅 2026-06-04

How to Fix: How do you get a Golang program to print the line number of the error it just called?

To get the line number of the error in a Golang program, use the runtime debugging package and its Println function with the -line option.

Quick Answer: Use runtime/debug.Println with the -line option to print the line number where an error occurred.

When writing error-handling code in Go, it can be frustrating when the program terminates abruptly without providing any information about the cause of the error. In this guide, we will explore how to get the line number where an error was called.

The `log.Fatal` function is commonly used for error handling, but it does not provide the line number where the error occurred.

💡 Why You Are Getting This Error

  • The main reason why this issue occurs is that Go's `log.Fatal` function only prints the error message and exits the program without providing any additional information.
  • Another possible cause could be related to how you are calling `log.Fatal` in your code. Make sure you are passing the correct arguments.

🚀 How to Resolve This Issue

Using the `debug.PrintStack` function

  1. Step 1: To get the line number where an error was called, you can use the `debug.PrintStack` function.
  2. Step 2: This function prints a stack trace of the current goroutine, which includes the line numbers of all functions that were called leading up to the error.
  3. Step 3: Here is an example of how to use it: `debug.PrintStack()`. This will print the stack trace to the console.

Using a custom error type

  1. Step 1: Another way to get the line number where an error was called is by creating a custom error type that includes the line number.
  2. Step 2: You can use the `errors.New` function to create a new error with a custom message, including the line number.
  3. Step 3: Here is an example: `func MyFunction() { errors.New("Error at line 10").Fatal()`}
  4. Step 4: This will print the error message and include the line number where the error occurred.

✨ Wrapping Up

In conclusion, there are two ways to get the line number where an error was called in Go: using the `debug.PrintStack` function or creating a custom error type. By following these methods, you can provide more information about the cause of errors in your program and make it easier to debug.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions