简体   繁体   中英

fetch function keeps throwing GET http://localhost:9000/Image.png 404 (Not Found) error in the browser even when i catch it

I have a folder of a bunch of images. And i want to delete unnecessary ones to save some memory and fetch time. I cant check if i need the image or not before the fetch. I can only know if i need it if the image is there or not. If the image is not there i want to just return null otherwise i wanna return HTMLImageElement with the image src.

I have a function thats responsible for cashing images.

async getCashedImage() {
    try {
        const blob = await this.getRequestedImage(imgURL,{method: "GET"}) 
        const imgObjectUrl = URL.createObjectURL(blob)
                    let img = new Image()
                    img.src = imgObjectUrl
                    this.imageMap.set(key, img)
                    this.fetchQueue = this.fetchQueue.filter((val) => {
                        return val != key
                    })
                    return img
    } catch (error) {
        return null
    }
}

And i have a function for getting those images.


private async getRequestedImage(url: string, config: RequestInit) : Promise<Blob> {
    const response = await fetch(url,config)
    if(!response.ok) {
        throw new Error(response.statusText)
    }
    return await response.blob()
}

And whatever i try to do i keep getting the GET http://localhost:9000/Image.png 404 (Not Found) error in console.

I just want the function to return null and not throw an error in case there is no image found.

Edit : Let me rephraze my question. Im getting the 404 response, throwing an error and catching it actually but the error still gets thrown in the console like i didnt catch it.

Took me hours to find this. But apparently if the image doesnt exist and you try to fetch it even if you handle to 404 the browser will still display an error on its own. So its more of a browser thing then the actuall code....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM