A Missing Null Check Caused a Full-Site White Screen: The Hidden Cost of 'Defensive' Frontend Code
It was a sunny Friday afternoon. I was about to commit my last line of code and enjoy the weekend.
Suddenly, the testers sent three bomb emojis in the group chat, followed by tagging the entire frontend team: "The production backend is down! Large-scale white screen, users can't even get to the login page!"
My hand trembled, nearly knocking over my thermos. I opened the production link, pressed F12, and in the Network panel, all APIs returned 200. The Console panel was clean, not a single red error.
But the page was dead white, mocking me like a tombstone.
As a somewhat senior frontend developer, my first instinct: the code threw an uncaught exception, causing the React/Vue render tree to crash.
But why were there no error logs? Our Sentry monitoring was eerily silent.
1. The Difficult Debugging: The Missing Error
I quickly rolled back the day's release, and the page immediately recovered. But that meant the problem was in today's code.
I pulled the code and started reviewing line by line. Three hours later, I stared at a piece of code on the screen, almost choked:
// New feature: read user UI preference config from LocalStorage
const prefString = localStorage.getItem('ui_preferences');
// get config
const preferences = JSON.parse(prefString);
// render logic
<ThemeProvider value={preferences.theme}>
Case solved.
This morning, a colleague, while fixing a bug, added logic that clears the ui_preferences key from LocalStorage under certain specific operations.
So when users (especially old users) refreshed the page again, prefString became null.
Then JSON.parse(null) became null.
Then in the render phase, preferences.theme became null.theme.
Directly throwing TypeError: Cannot read properties of null.
Why didn't Sentry catch it? Because the exception happened in the render phase of a React component. In development, React has an Error Boundary fallback that shows an error page. But in our production configuration, to 'prevent sensitive information leakage,' some deep errors were intercepted, causing the entire application to silently crash.
A missing null check, one line short, ruined a weekend.
2. The Trap of Over-Defense: Is Your try...catch Really Useful?
At the post-incident review meeting, the director asked a profound question: "We've written a lot of defensive code, why didn't it catch this?"
Everyone looked at each other.
Yes, for 'defense,' we had made many efforts before. For example, wrapping all API requests in try...catch, adding lots of ?. (optional chaining) where errors might occur.
But this incident made me realize an counterintuitive truth: many times, what frontend calls 'defensive programming' is essentially just 'covering your ears while stealing a bell.'
Counterintuitive #1: Abuse of try...catch Creates Bigger Disasters
Have you ever written code like this:
try {
const data = JSON.parse(res.data);
// execute extremely complex business logic, modify global state
store.update(data);
} catch (e) {
console.log("parse failed", e);
}
On the surface, you caught the exception, and the page won't white-screen.
But in reality, your business logic is interrupted. The user clicked 'Submit Order,' the order was actually created on the backend, but because the parsing error wasn't handled well, the frontend showed a 'network error,' so the user clicks again. You hid the real error, leading to dirty data or even duplicate charges.
Advanced defense is not 'swallow everything,' but 'intercept at the source, degrade at the boundary.'
Counterintuitive #2: Optional Chaining ?. Is Not a Silver Bullet
To prevent errors, people scatter ?. everywhere.
const userName = user?.info?.name;
This indeed prevents Cannot read properties of undefined.
But it doesn't prevent business empty states. When userName is undefined, the UI might just show a blank avatar and name. The user is confused, perhaps thinking the network is slow.
Shouldn't the right approach be to give the UI a clear fallback (like 'unnamed user' or a skeleton screen)?
3. How to Build a Real 'Frontend Fallback System'?
After this incident, I spent a week refactoring the team's frontend defense system. I summarized it as 'Three Lines of Defense'.
First Line: Data Boundary Validation (Don't Trust the Backend, Don't Trust the Cache Either)
Never trust any external input, including localStorage, sessionStorage, URL parameters, even backend responses.
Now, we added SafeParse at the project entry:
const getSafePreferences = () => {
try {
const raw = localStorage.getItem('ui_preferences');
if (!raw) return DEFAULT_PREFERENCES; // must have default fallback
const parsed = JSON.parse(raw);
// validate data type, prevent dirty data from crashing UI
return { ...DEFAULT_PREFERENCES, ...parsed };
} catch {
return DEFAULT_PREFERENCES;
}
}
Good defense ensures the app can survive with minimum functionality under any external data.
Second Line: Error Boundary
In React, always wrap ErrorBoundary around the outermost and key business modules. In Vue, use app.config.errorHandler for global catching.
But the key is: errors in production must be reported, and UI must degrade.
When a component crashes, don't show a desperate white screen; instead show a card saying 'Module failed to load, click to retry.' That's called graceful degradation.
Third Line: Safety Net During Release
Often white screens aren't logic problems but deployment issues (e.g., after release, the old page's hash file is missing, causing chunkloaderror).
We introduced release overload monitoring and globally listen for window.addEventListener('unhandledrejection'). Once resource fetching fails, automatically execute window.location.reload(). The user might briefly flash a black screen but won't be stuck on a white screen.
4. In Conclusion: Great Frontend Developers Do 'Useless Work'
Nowadays on Juejin, everyone talks about AI efficiency, Rust refactoring toolchains, 3D, and micro-frontends. All good.
But if you ask an old frontend developer who has worked for a decade and truly led a business line: "What do you think is the most important technical skill?"
They'll likely tell you: the ability to write stable code that withstands all network fluctuations, dirty data, and edge cases.
Frontend engineering, after all, is the 'last line of defense for user experience.'
AI can generate a beautiful CRUD form in a second, but it might not know that when localStorage is empty, you need to insert a default config.
Rust can speed up build times 20x, but it can't prevent third-party APIs from returning dirty data.
Truly valuable frontend work is often dozens of lines of 'seemingly useless' defensive code written silently where users can't see.
Top 2 from juejin.cn, machine-translated. The original thread is authoritative.
I agree with the boundary validation part. The default value for localStorage should not fall back to an object. My current approach is to funnel all local reads through a `readJson(key, schema)` function: first check for null, then parse, then use the schema to fill in defaults. ErrorBoundary should only be the last line of defense, not a substitute for data boundaries. I'd like to ask: in your first line of defense, is the schema defined with zod or handwritten assertions? And when you encounter dirty data from an old version, do you discard it directly or migrate it?
No problem there, swallowing exceptions is the real pitfall. A white screen is not scary; silent crashes are what's fatal.