skip to Main Content

I would like to display more than just one sentence(i.e. Error title, error description and error cause).

I tried to extend basic Error class and add there two custom properties, but I can’t access them in error.tsx file. Any ideas how to deal with it?

2

Answers


  1. Check this link

    If you have no error.tsx(js), just create the file (error.js) in the app folder with the following content

    'use client' // Error components must be Client Components
     
    import { useEffect } from 'react'
     
    export default function Error({ error, reset }) {
      useEffect(() => {
        // Log the error to an error reporting service
        console.error(error)
      }, [error])
     
      return (
        <div>
          <h2>Something went wrong!</h2>
          <button
            onClick={
              // Attempt to recover by trying to re-render the segment
              () => reset()
            }
          >
            Try again
          </button>
        </div>
      )
    } 
    

    Update:

    import { useEffect } from 'react';
    import useSWR from 'swr';
    
    export default function Error({ error, reset }) {
      // Fetch data from your API
      const { data, error: apiError } = useSWR('/api/your-api-endpoint');
    
      useEffect(() => {
        // Log the error to an error reporting service
        console.error(error);
      }, [error]);
    
      // Optional: Handle API errors
      if (apiError) return <div>Failed to load data from API</div>;
    
      // Display API message if available, otherwise show a generic message
      const messageFromApi = data?.message || 'Something went wrong!';
    
      return (
        <div>
          <h2>{messageFromApi}</h2>
          <button onClick={() => reset()}>
            Try again
          </button>
        </div>
      );
    }
    

    Dont forget to instal useSWR

    Login or Signup to reply.
  2. you should try separate your data with signs or to use JSON.Stringify, I give you both examples:

    OPCION 1 :

    const errorString ="title:this is title&description:this is description&errorCode:501";
    
    let listErrors=errorString.split("&");
    listErrors=listErrors.map((er)=>er.split(":"));
    
    let error = {}
    listErrors.forEach((er)=>{
       error[er[0]]=er[1]
    })
    
    //esta seria tu salida
    console.log(error)

    OPCION 2 : JSON.parce and JSON.stringify

    const infoError={
      title:"this is a Title",
      description:"this is a description",
      errorCode:"504",
    }
    
    const errorString=JSON.stringify(infoError)
    ///this pased to function error☝
    
    
    ///in error.tsx decode string👇
    const resultError=JSON.parse(errorString)
    
    console.log(resultError)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search