Skip to content

Commit

Permalink
refactor: Improve error handling in useSpriteLoader (#2105)
Browse files Browse the repository at this point in the history
This commit refactors the useSpriteLoader function to improve error handling when loading standalone sprites. Previously, if neither the textureUrl nor the input was provided, the function would silently fail. Now, it throws an error indicating that either the textureUrl or the input must be provided. Additionally, if an invalid texture URL is provided, it throws an error indicating that a valid texture URL must be provided. The error handling has been enhanced to provide more informative error messages.

These changes aim to make the useSpriteLoader function more robust and provide better error feedback to developers.
  • Loading branch information
hichemfantar authored Sep 24, 2024
1 parent 5710ce5 commit ea68700
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/core/useSpriteLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,20 @@ export function useSpriteLoader<Url extends string>(
}

function loadStandaloneSprite(textureUrl?: string) {
if (textureUrl || input) {
new Promise<THREE.Texture>((resolve) => {
textureLoader.load(textureUrl ?? input!, resolve)
}).then((texture) => {
parseSpriteData(null, texture)
})
if (!textureUrl && !input) {
throw new Error('Either textureUrl or input must be provided')
}

const validUrl = textureUrl ?? input
if (!validUrl) {
throw new Error('A valid texture URL must be provided')
}

new Promise<THREE.Texture>((resolve) => {
textureLoader.load(validUrl, resolve)
}).then((texture) => {
parseSpriteData(null, texture)
})
}

/**
Expand Down Expand Up @@ -203,7 +210,11 @@ export function useSpriteLoader<Url extends string>(
const getRowsAndColumns = (texture: THREE.Texture, totalFrames: number) => {
if (texture.image) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')!
const ctx = canvas.getContext('2d')

if (!ctx) {
throw new Error('Failed to get 2d context')
}

canvas.width = texture.image.width
canvas.height = texture.image.height
Expand Down

0 comments on commit ea68700

Please sign in to comment.