Sitemap
Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Follow publication

Best Practices in Handling Errors in Web Components

7 min readJan 27, 2023

--

What Causes Errors in Web Components?

Best Practises in Error Handling

Using Try-Catch Blocks

try {
// business operation
} catch(err){
// in case of error

console.log(err)
}
const onMenuClick = () => {
try {
console.log("Menu clicked");
throw new Error("Menu clicked");
console.log("Menu clicked");
} catch (err) {
console.error(err);
}
};

Using Optional Checks

const UserCard = () => {
const [user, setUser] = useState(undefined);

// will throw an error since user is undefined

return <div>{user.name}</div>;
};
const UserCard = () => {
const [user, setUser] = useState(undefined);

if (!user) {
return <div>Loading...</div>;
}
return <div>{user.name}</div>;
};
const UserCard = () => {
const [user, setUser] = useState(undefined);

return <div>{user?.name || 'Not Available'}</div>;
};

Using Error Boundaries

class MyCustomErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error) {
// update the error state to show the error UI

return { hasError: true };
}

componentDidCatch(error, errorInfo) {
// do additional error handling logic here

console.log(error, errorInfo);
}

render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <p>Error.Rendering Fallback UI for Error.</p>;
}
return this.props.children;
}
}
<MyCustomErrorBoundary>
{children}
</MyCustomErrorBoundary>

Final Thoughts

Medium Logo
Medium Logo

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Bits and Pieces
Bits and Pieces

Published in Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Lakindu Hewawasam
Lakindu Hewawasam

Written by Lakindu Hewawasam

AWS Certified | AWS Community Builder — Serverless | LinkedIn: https://www.linkedin.com/in/lakindu-hewawasam/

No responses yet

Write a response