better error handling

This commit is contained in:
smolgrrr 2024-04-19 19:32:38 +10:00
parent 91311e6346
commit 26ac3824cc

View File

@ -4,20 +4,32 @@ import { useState, useEffect } from 'react';
const LinkModal = ({ url }: { url: string }) => { const LinkModal = ({ url }: { url: string }) => {
const [linkPreview, setLinkPreview] = useState<LinkPreview | null>(null); const [linkPreview, setLinkPreview] = useState<LinkPreview | null>(null);
const [error, setError] = useState<string | null>(null);
const fetchWithProxy = (url: string) => {
const proxyUrl = 'https://api.allorigins.win/raw?url=';
return getLinkPreview(proxyUrl + url)
.then((preview) => setLinkPreview(preview as LinkPreview))
.catch((error) => {
console.error("Error fetching URL with proxy:", error);
setError('Unable to fetch URL with proxy.');
});
};
useEffect(() => { useEffect(() => {
const proxyUrl = 'https://api.allorigins.win/raw?url=';
getLinkPreview(url) getLinkPreview(url)
.then((preview) => setLinkPreview(preview as LinkPreview)) .then((preview) => setLinkPreview(preview as LinkPreview))
.catch(error => { .catch(error => {
console.error("Error fetching original URL, trying with proxy:", error); console.error("Error fetching original URL, trying with proxy:", error);
return getLinkPreview(proxyUrl + url); setError('Error fetching original URL. Trying with proxy...');
}) return fetchWithProxy(url);
.then((preview) => setLinkPreview(preview as LinkPreview)) });
.catch((error) => console.error("Error fetching URL with proxy:", error));
}, [url]); }, [url]);
if (error) {
return <div>Error: {error}</div>; // Display a user-friendly error message
}
if (!linkPreview) { if (!linkPreview) {
return <a className='hover:underline text-xs text-neutral-500' href={url}>{url}</a>; // or some loading state return <a className='hover:underline text-xs text-neutral-500' href={url}>{url}</a>; // or some loading state
} }