<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adarsh Rishishwar on Medium]]></title>
        <description><![CDATA[Stories by Adarsh Rishishwar on Medium]]></description>
        <link>https://medium.com/@adarsh.rishishwar?source=rss-baa63a75c8a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0OUQzyJktuJriU_e</url>
            <title>Stories by Adarsh Rishishwar on Medium</title>
            <link>https://medium.com/@adarsh.rishishwar?source=rss-baa63a75c8a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 00:07:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adarsh.rishishwar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Error Handling in Frontend Applications: A Comprehensive Guide]]></title>
            <link>https://medium.com/carousell-insider/mastering-error-handling-in-frontend-applications-a-comprehensive-guide-2df73846385b?source=rss-baa63a75c8a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df73846385b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Adarsh Rishishwar]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 08:25:16 GMT</pubDate>
            <atom:updated>2024-03-07T08:28:06.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Welcome to the enchanted world of frontend development, where applications come to life with vibrant user interfaces and dazzling features. However, just like any adventure, this journey is not without its challenges. One of the most formidable foes you’ll encounter is the elusive and unpredictable “Error.” In this blog post, we’ll equip you with the knowledge and tools to conquer these errors and create a seamless user experience in your frontend application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ogOoE_T8Z6jsVtf8_xl0w.jpeg" /><figcaption>Our Beautiful project under attack from Errors — Photo by Craig Adderley from Pexels</figcaption></figure><h3>Chapter 1: Meet the Heroes — CustomError and Its Companions</h3><p>In our quest to tame errors, we begin by crafting a team of trusty companions led by “CustomError”. Much like a wizard’s staff, CustomError extends the built-in JavaScript <em>“Error”</em> object to suit our application’s unique needs. With its magical properties like <em>“code”</em> and <em>“data”,</em> we can convey precise information about the error to aid in debugging.</p><pre>export class CustomError extends Error {<br>  code<br>  data<br>  constructor(code: string, message: string, data?: any) {<br>    super(message)<br>    // error doesn&#39;t pass to the prototype chain with typescript if target is less than es6<br>    // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work<br>    this.name = code<br>    this.code = code<br>    this.data = data<br>  }<br>}<br><br>export function isCustomError(candidate: any): candidate is CustomError {<br>  return candidate instanceof CustomError || &quot;code&quot; in candidate<br>}</pre><p>But CustomError is not alone on this journey. It spawns a legion of specialised error classes like “AuthenticationError”, “AuthorisationError”, “NotFoundError” and multiple corps. Each class has a distinct purpose, making it easier to discern and handle errors gracefully.</p><pre>export class NotFoundError extends CustomError {<br>  constructor(message = &quot;404 - Not Found&quot;, data?: any) {<br>    super(ERROR_CODES.NOT_FOUND, message, data)<br>  }<br>}<br><br>export function isNotFoundError(candidate: any): candidate is NotFoundError {<br>  return (<br>    candidate instanceof NotFoundError ||<br>    candidate?.code === ERROR_CODES.NOT_FOUND<br>  )<br>}</pre><h3>Chapter 2: Mastering API Layer Error Handling</h3><p>In our quest for error handling mastery, we must not forget the critical role played by the API layer. This layer acts as a gateway to external resources and services, making it essential to handle errors effectively.</p><pre>const GeneralErrorMessage =<br>  &quot;Error: Please refresh and try again, or contact the support team.&quot;;<br><br>export const errorHandler = (error) =&gt; {<br>  const { request, response, code } = error;<br>  if (code) {<br>    if (code === &quot;ECONNABORTED&quot;)<br>      throw new ServiceError(&quot;The server is taking too long to respond!&quot;);<br>  }<br>  if (response) {<br>    const { data, status } = response;<br>    const readableError = getReadableError(status, data);<br>    throw readableError;<br>  } else if (request) {<br>    // Request sent but no response received<br>    throw new ServiceError(GeneralErrorMessage);<br>  } else {<br>    const { status } = { ...error.toJSON(), ...{ status: 500 } };<br>    const readableError = getReadableError(status);<br>    throw readableError;<br>  }<br>};<br>const getReadableError = (status: number, data?: any) =&gt; {<br>  if (status &lt;= 500) {<br>    if (status === 404)<br>      return new NotFoundError(data?.errorMsg ?? ErrorMessages[404])<br>    if (status === 500)<br>      return new ServiceError(data?.errorMsg ?? ErrorMessages[500])<br>    if (status === 401)<br>      return new AuthenticationError(data?.errorMsg ?? ErrorMessages[401])<br>    if (status === 403)<br>      return new AuthorisationError(data?.errorMsg ?? ErrorMessages[403])<br>    if (status === 409 || status === 422)<br>      return new ValidationError(data?.errorMsg ?? ErrorMessages[409])<br>    return new ClientError(data?.errorMsg ?? ErrorMessages[status])<br>  }<br>  return new ServiceError(data?.errorMsg ?? GeneralErrorMessage, data)<br>}</pre><p>Our API error handler examines the error object, handles different error scenarios, and throws custom error classes for specific situations, ensuring a consistent and structured approach to error handling.</p><h3>Chapter 3: Managing the Kingdom — State Management for Errors</h3><p>In the sprawling kingdom of frontend development, you’ll encounter a diverse array of errors. To rule with wisdom and grace, you must manage these errors with precision. That’s where state management systems like Redux come into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBeBKJmxlnDIqlPS3BqsXA.jpeg" /><figcaption>Photo by clark cruz</figcaption></figure><p>By integrating state management, you can seamlessly propagate errors to the state, enabling real-time feedback to users. Whether it’s gracefully handling unexpected errors or providing informative messages, a well-structured error handling strategy ensures a harmonious kingdom.</p><pre>export const errorSlice = createSlice({<br>  name: ERROR_SLICE_NAMESPACE,<br>  initialState,<br>  reducers: {<br>    setError(<br>      state,<br>      { payload: { code, message, data } }: PayloadAction&lt;ErrorState&gt;<br>    ) {<br>      state.code = code<br>      state.message = message<br>      state.data = data<br>    },<br>    clearError(state) {<br>      const { code, message, data } = initialState<br>      state.code = code<br>      state.message = message<br>      state.data = data<br>    },<br>  },<br>})</pre><h3>Chapter 4: Intercepting Errors on the Battlefield — Redux Saga</h3><p>Our journey takes us to the battlefield where API errors are formidable adversaries. To centralise API error handling, we call upon the wise sorcerer known as “Redux Saga”. With its mystical abilities, Redux Saga intercepts HTTP requests and responses, applying common error-handling logic.</p><pre>const sagaTask = sagaMiddleware.run(saga)<br>sagaTask.toPromise().catch((error) =&gt; {<br>  //dispatch appropriate actions to set error state<br>  store.dispatch(setError(error))<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nf6pFSS7GSvTcViwcRSBCw.jpeg" /><figcaption>Saga at Action- Photo by Levi Damasceno</figcaption></figure><p>Let’s dive into a practical example — adding a new item to your application using Redux Saga:</p><pre>export function* addNewItem(action) {<br>  const { payload: { name } } = action;<br>  <br>  // Update the UI state to indicate item addition is in progress<br>  yield put(addNewItemPending());<br>  <br>  // Invoke the API to add a new item<br>  const data = yield call(ItemsClient.addNewItem, {<br>    data: { name },<br>  });<br>  <br>  if (data?.id) {<br>    // Update UI state with success status<br>    yield put(addNewItemSuccess());<br>    // Display success message to the user<br>    yield put(showToastMessageAction({<br>      type: &quot;success&quot;,<br>      message: `Successfully added item: ${name}!`,<br>    }));<br>  } else {<br>    throw new IAMError(&quot;Couldn&#39;t add new item&quot;);<br>  }<br>}</pre><p>In this example, we add a new item using Redux Saga. We update the UI state, make an API call, and handle success and error scenarios. Redux Saga allows us to throw appropriate errors, then we can dispatch these errors with actions to the Redux store, and manage them using our error state management solution, providing a unified approach to error handling.</p><h3>Chapter 5: Error Boundaries — The Shields of Your Application</h3><p>In the land of frontend development, errors can be treacherous beasts that threaten to crash your entire application. Fear not! We introduce you to the magical shields known as “Error Boundaries.” These guardians, inspired by React, encase parts of your application and shield them from the devastating effects of errors.</p><pre>interface Props extends PropsFromRedux {<br>  children: React.ReactNode<br>  ifNotAuthenticated: () =&gt; void<br>  onSupportClick: (errorMessage?: string) =&gt; void<br>}<br><br>class ModuleErrorBoundary extends Component&lt;Props&gt; {<br>  state: {<br>    error: Error | null<br>    errorInfo: ErrorInfo<br>    hasError: boolean<br>  }<br>  // triggered when the error is caught while rendering<br>  static getDerivedStateFromError(error: Error) {<br>    // set correct state for the next render<br>    return { hasError: true, error }<br>  }<br>  // triggered when the error is updated in our store<br>  static getDerivedStateFromProps(props: Props) {<br>    const { error } = props<br>    logger.info(error)<br>    if (error.code) return { hasError: true, error }<br>    return null<br>  }<br>  constructor(props: Props) {<br>    super(props)<br>    this.state = {<br>      hasError: false,<br>      errorInfo: { componentStack: &quot;&quot; },<br>      error: null,<br>    }<br>  }<br>  // logging the error<br>  componentDidCatch(error: Error, errorInfo: ErrorInfo) {<br>    logger.error(error)<br>    logger.error(errorInfo.componentStack)<br>  }<br>  render(): ReactNode {<br>    const { hasError, error } = this.state<br>    const { ifNotAuthenticated, children, onSupportClick } = this.props<br>    if (hasError) {<br>      if (isAuthenticationError(error) &amp;&amp; ifNotAuthenticated)<br>        ifNotAuthenticated()<br>      const message = isCustomError(error)<br>        ? error.message<br>        : `Sorry, something went wrong<br>Try to refresh the page or contact your admin`<br>      return (<br>        &lt;&gt;<br>          &lt;Box<br>            sx={{<br>              alignItems: &quot;center&quot;,<br>              justifyContent: &quot;center&quot;,<br>              display: &quot;flex&quot;,<br>              height: &quot;100%&quot;,<br>            }}<br>          &gt;<br>            &lt;Stack spacing={4}&gt;<br>              &lt;Image alt=&quot;Error Image&quot; loader={CustomLoader} src={ErrorImage} /&gt;<br>              &lt;P align=&quot;center&quot; variant=&quot;caption&quot;&gt;<br>                {message}<br>              &lt;/P&gt;<br>              {isNotFoundError(error) || isClientError(error) ? (<br>                &lt;Button<br>                  icon={<br>                    &lt;Image<br>                      alt=&quot;reload&quot;<br>                      loader={CustomLoader}<br>                      src={RealoadIcon}<br>                    /&gt;<br>                  }<br>                &gt;<br>                  {RETRTY_LABEL}<br>                &lt;/Button&gt;<br>              ) : (<br>                &lt;Button<br>                  color=&quot;secondary&quot;<br>                  icon={<br>                    &lt;Icon variant=&quot;ContactSupportOutlined&quot; fontSize=&quot;small&quot; /&gt;<br>                  }<br>                  onClick={() =&gt; onSupportClick(error?.message)}<br>                  variant=&quot;text&quot;<br>                &gt;<br>                  {SUPPORT}<br>                &lt;/Button&gt;<br>              )}<br>            &lt;/Stack&gt;<br>          &lt;/Box&gt;<br>        &lt;/&gt;<br>      )<br>    }<br>    return children<br>  }<br>}<br>const mapState = (state: AppState) =&gt; ({ error: state.ERROR_SLICE })<br>const mapDispatch = {<br>  clearError,<br>}<br>const connector = connect(mapState, mapDispatch)<br>type PropsFromRedux = ConnectedProps&lt;typeof connector&gt;<br>export const ConnectedModuleErrorBoundary = connector(ModuleErrorBoundary)</pre><p>With Error Boundaries in place, your application can gracefully handle errors, display user-friendly messages, and offer options for recovery, much like a seasoned knight defending the kingdom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AYahRacMDT-oIR_KiBLEQ.jpeg" /><figcaption>Error Boundaries — Photo by Aleksandar Pasaric</figcaption></figure><h3>Chapter 6: Applying Error Handling in Practice</h3><p>Now that we’ve armed ourselves with the knowledge and tools for error handling in frontend development, let’s put it all into practice using a real-world example. Imagine you have a saga responsible for adding a new item to your application. We’ll walk you through how to apply the error handling techniques we’ve discussed.</p><pre>export function* addNewItem(action: PayloadAction&lt;AddItemRequest&gt;) {<br>  try {<br>    const {<br>      payload: { name },<br>    } = action;<br><br>    // Update the UI state to indicate that item addition is in progress<br>    yield put(addNewItemPending());<br>    // Invoke the API to add a new item<br>    const data = yield call(ItemsClient.addNewItem, {<br>      data: {<br>        name,<br>      },<br>    });<br>    if (data?.id) {<br>      // Update the UI state with a success status<br>      yield put(addNewItemSuccess());<br>      // Display a success toast message to the user<br>      yield put(<br>        showToastMessageAction({<br>          type: &quot;success&quot;,<br>          message: `Successfully added item: ${name}!`,<br>        })<br>      );<br>      // Refresh the data in the items table or take other necessary actions<br>      // (e.g., navigating to a different page)<br>      // yield put(refreshItemsTableAction());<br>    } else {<br>      // If the API response does not contain an &#39;id&#39;, throw a custom IAMError<br>      throw new IAMError(&quot;Couldn&#39;t add new item&quot;);<br>    }<br>  } catch (err) {<br>    // Handle errors and update the UI state accordingly<br>    yield put(addNewItemFailed());<br>    // Handle specific error types (IAMError, ValidationError, etc.)<br>    if (!isIAMError(err) &amp;&amp; !isValidationError(err)) {<br>      // If it&#39;s not one of the expected error types, propagate the error further<br>      throw err;<br>    }<br>    // Display user-friendly error messages based on the error type<br>    if (isValidationError(err)) {<br>      // Display a validation error toast message<br>      yield put(<br>        showToastMessageAction({<br>          type: &quot;error&quot;,<br>          message: &quot;This item already exists!&quot;,<br>        })<br>      );<br>    } else if (isIAMError(err)) {<br>      // Display a generic IAM error toast message<br>      yield put(<br>        showToastMessageAction({<br>          type: &quot;error&quot;,<br>          message: &quot;Couldn&#39;t add new item. Please try again later.&quot;,<br>        })<br>      );<br>    }<br>  }<br>}</pre><p>In this example, we’ve got a saga that adds a new item to your application. Here’s how you can use the error handling techniques we’ve discussed:</p><ul><li>We start by updating the UI state to indicate that the item addition is in progress (addNewItemPending()).</li><li>We then make an API call to add the new item and check if the operation was successful by inspecting the API response.</li><li>If the response contains an ‘id,’ we update the UI state with a success status (addNewItemSuccess()), display a success toast message to the user, and potentially take other necessary actions like refreshing the data.</li><li>If the response does not contain an ‘id,’ we throw a custom IAMError to handle this specific error case. This allows us to gracefully manage the error and provide user-friendly feedback.</li><li>In the catch block, we handle errors, update the UI state with a failure status (addNewItemFailed()), and display user-friendly error messages based on the error type (validation error or IAM error).</li><li>If any unexpected error is found we throw it again. This error is caught by our Saga Middleware, which dispatches an action and updates the state with caught errors. This state is subscribed to by our error boundaries, which in turn can show the correct error views.</li></ul><p>By following this example, you can apply the error handling techniques we’ve discussed to real-world scenarios in your frontend application, ensuring a smooth user experience and robust error management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyyaPwiMnQb4Bi4TgasVDw.jpeg" /><figcaption>Celebrations — Photo by Rick Han</figcaption></figure><h3>Conclusion: A Hero’s Journey</h3><p>As we conclude our adventure through the enchanted world of frontend development, you’ve learned to wield the mighty “CustomError” and its companions, shield your application with Error Boundaries, harness the power of Redux Saga, and govern your kingdom with state management.</p><p>Mastering error handling in frontend applications is not just about defeating errors, but also about enhancing the user experience and ensuring the stability of your software. Armed with these tools and techniques, you’re now prepared to face any error that crosses your path on your heroic journey through frontend wonderland.</p><p>In the next instalment of our blog series, we’ll embark on a quest to explore the hidden realm of error logging and reporting. Join us as we uncover valuable insights into the errors lurking in your frontend application. Until then, happy coding and may your code be bug-free!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df73846385b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carousell-insider/mastering-error-handling-in-frontend-applications-a-comprehensive-guide-2df73846385b">Mastering Error Handling in Frontend Applications: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/carousell-insider">Carousell Insider</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>