View : 0

12/04/2026 18:17pm

JS2GO EP.28 Advanced Error Handling: Stack Trace and Logging

JS2GO EP.28 Advanced Error Handling: Stack Trace and Logging

#Go

#JavaScript

#Logging

#Stack Trace

#Errors

Error handling is a crucial part of professional software development, especially in large-scale systems or production environments where you need to debug and analyze issues efficiently. In this article, we explore advanced error handling in JavaScript and Go, including the use of stack traces and logging to analyze and resolve errors effectively.

 

1. Errors and Stack Trace in JavaScript

 

Creating and Handling Errors

function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

try {
  const result = divide(10, 0);
} catch (err) {
  console.error("Error:", err.message);
  console.error(err.stack); // Display stack trace
}

 

Advantages:
✔️ Stack trace shows exactly where the error occurred
✔️ Error objects can be extended with custom properties
✔️ Easy to use for debugging

 

Limitations:
⚠️ Runtime errors must be handled with try/catch
⚠️ Asynchronous code requires try/catch + async/await or .catch()

 

Handling Asynchronous Errors

async function fetchData() {
  throw new Error("Network error");
}

fetchData()
  .then(data => console.log(data))
  .catch(err => console.error(err.stack));

 

2. Errors and Stack Trace in Go

 

Using the error Type

package main

import (
    "errors"
    "fmt"
)

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }
}

 

Creating a Stack Trace

Go does not provide automatic stack traces like JavaScript, but you can use the runtime/debug package:

import (
    "errors"
    "fmt"
    "runtime/debug"
)

func main() {
    err := errors.New("something went wrong")
    if err != nil {
        fmt.Println("Error:", err)
        fmt.Println(string(debug.Stack()))
    }
}

 

Advantages:
✔️ Type-safe and ensures error handling at compile time
✔️ Allows adding context using fmt.Errorf("context: %w", err)
✔️ Works well with logging libraries such as logrus or zap

 

Limitations:
⚠️ Stack trace must be explicitly captured
⚠️ Error handling requires returning and checking every error

 

3. Combining Logging with Errors

 

JavaScript + Logging (Winston)

const winston = require('winston');

const logger = winston.createLogger({
  transports: [new winston.transports.Console()]
});

try {
  throw new Error("Something went wrong");
} catch (err) {
  logger.error(err.message, { stack: err.stack });
}

 

Go + Logging (Logrus)

import log "github.com/sirupsen/logrus"

func main() {
    err := errors.New("Something went wrong")
    if err != nil {
        log.WithFields(log.Fields{
            "stack": string(debug.Stack()),
        }).Error(err)
    }
}

 

4. Best Practices

 

✔️ Fully utilize the Error object / error type
✔️ Add context to errors to make debugging easier
✔️ Capture stack traces when errors occur
✔️ Combine with logging to record events and error locations
✔️ Separate error handling by environment:

  • Development: log + full stack trace
  • Production: log summary + alerts

 

5. JavaScript vs Go: Error Handling Comparison

 

FeatureJavaScriptGo
Error TypeError objecterror interface
Stack TraceAutomatic (err.stack)runtime/debug.Stack()
Logging IntegrationWinston, Pinologrus, zap
Error ContextCan add properties dynamicallyUse fmt.Errorf or wrap errors
Async Handlingtry/catch + async/awaitReturn error from function

 

Recommendations:
✔️ Web apps / frontend-heavy → JavaScript with stack trace + logging
✔️ Backend / server → Go with error + logging + stack trace

 

Combining stack trace with structured logging allows professional debugging and monitoring in production environments.

 


 

Next Episode

 

In EP.29 of the JS2GO series, we will learn Signal and Process Management in Go and JavaScript to control process lifecycle, handle signals, and manage application operations safely and correctly.

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en