How to handle error in useGLTF

Hi guys,

I try to load an OBJ file stored on S3. When the file is not there the page crashes:
Is there a way to handle errors in this hook?
I will use this example in CodeSandbox React Three Fiber Boilerplate - useGLTF - CodeSandbox

const Models = [
  {
    title: 'Hammer',
    url:
      'https://cdn.jsdelivr.net/gh/Sean-Bradley/React-Three-Fiber-Boilerplate@useGLTF/public/models/hammer.glb'
  },
  
]

function Model({ url }) {
  const { scene } = useGLTF(url)
  return <primitive object={scene} />
}

Once url is not right, it will give the error “Could not load”. I was wondering if it can give me an error message, so I could show this alert, but not crash the app. Thanks.

useGLTF is for loading gltf and glb files.

To load an obj, use something like,

import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
import { useLoader } from '@react-three/fiber'

function Model() {
  const obj = useLoader(OBJLoader, '/model.obj')
  return <primitive object={obj} />
}

you catch errors with error boundaries, like any other error.

codesandbox will still show the error overlay, ignore it and click the X and you will see the fallback. in prod you’d only see the fallback.

you can use error boundaries raw but i prefer this lib react-error-boundary - npm

this doesn’t look quite right, you’ve got an object as the function parameter, i may be mistaken when it comes to r3f but typically this should probably look like the following…

function Model( url ) {
  const { scene } = useGLTF(url)
  return <primitive object={scene} />
}

no no its correct. props are given as an object, and if you want to pull single values you would typically destruct

2 Likes

Thank for your solution, I don’t want overlay, I will try react-error-boundary to see what I get.

:woozy_face: R3f is just syntactical wizardry that just always seems to allude me

The same feeling as you :sweat_smile:

you do not normally get an overlay, this is coming from codesandbox. error boundaries is how you catch errors in react, it’s just that csb has this “feature” where they show that dialog. some bundlers do it as well. in prod you only have the fallback.