Blog>
Snippets

Handling Missing Source Maps

Showcase error handling and troubleshooting techniques when source maps are not correctly linked or missing from the browser's developer tools.
if (typeof Error.captureStackTrace === 'function') {
    Error.captureStackTrace(this, CustomError);
}
Extends the native Error object to capture the stack trace for better debugging. Checks if the captureStackTrace function is available before using it to avoid runtime errors.
window.onerror = function(message, source, lineno, colno, error) {
    console.error('An error occurred:', message, 'at', source + ':' + lineno + ':' + colno);
    if (error && !error.stack) {
        console.warn('Stack trace is not available.');
        // additional logic to handle missing stack trace
    }
    return true; // Prevent the firing of the default event handler
};
Global error handler to log error messages, locations, and stack traces. Warns if the stack trace is missing, which could indicate a missing source map. It also prevents the browser's default handler from running.
try {
    // Code that may throw an exception
} catch (error) {
    if (error.sourceURL && !error.stack) {
        console.warn('A source map might be missing or incorrect for', error.sourceURL);
    } else if (error instanceof ReferenceError) {
        console.error('ReferenceError occurred:', error.message);
    } else {
        console.error('An unexpected error occurred:', error);
    }
}
Catch block to handle exceptions that may happen within a try block. Checks if the error has a property sourceURL but lacks a stack trace, which might indicate a missing source map. Also demonstrates handling of specific error types.
fetch('/path/to/script.js.map')
    .then(response => response.json())
    .then(sourcemap => {
        // Use sourcemap as needed
    })
    .catch(error => {
        console.error('Failed to load source map:', error);
    });
Asynchronously loads a source map file using the Fetch API. Handles cases where the source map might not load due to network errors or incorrect paths.
if (new Error().stack) {
    console.log('Stack trace is supported.');
} else {
    console.warn('Stack traces are not supported in this environment.');
}
Feature detection to check if stack traces are supported in the current environment, providing a baseline to determine if a missing stack trace is a broader issue.