Personal Site

Handle exceptions in the SSE

vielle.dev 11459e8c cc79a25c

verified
+29 -20
+29 -20
src/pages/now-playing-sse.ts
··· 1 - import { nowPlaying } from "/components/playing/spotify"; 2 3 export async function GET() { 4 const update = async (): Promise<string> => { 5 // extract a subset to reduce size for client 6 // not huge savings but tesco yk 7 - const playing = await nowPlaying().then((playing) => 8 - playing 9 - ? { 10 - type: "track", 11 - id: playing.id, 12 - name: playing.name, 13 - album: { 14 - images: playing.album.images.map((x) => ({ 15 - url: x.url, 16 - width: x.width, 17 - height: x.height, 18 })), 19 - }, 20 - artists: playing.artists.map((x) => ({ 21 - name: x.name, 22 - id: x.id, 23 - })), 24 - } 25 - : null, 26 - ); 27 28 // SSE syntax: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format 29 return `event: playing\ndata: ${JSON.stringify(playing)}\n\n`;
··· 1 + import { spotifyNowPlaying, SpotifyError } from "/components/playing/spotify"; 2 3 export async function GET() { 4 const update = async (): Promise<string> => { 5 // extract a subset to reduce size for client 6 // not huge savings but tesco yk 7 + const playing = await spotifyNowPlaying() 8 + .then((playing) => 9 + playing 10 + ? { 11 + type: "track", 12 + id: playing.id, 13 + name: playing.name, 14 + album: { 15 + images: playing.album.images.map((x) => ({ 16 + url: x.url, 17 + width: x.width, 18 + height: x.height, 19 + })), 20 + }, 21 + artists: playing.artists.map((x) => ({ 22 + name: x.name, 23 + id: x.id, 24 })), 25 + } 26 + : null, 27 + ) 28 + .catch((err) => { 29 + if (!(err instanceof SpotifyError)) 30 + throw new Error("Unhandled exception"); 31 + console.error(err.code, err.human, err.details); 32 + 33 + if (err.code === "NO_CONTENT") return null; 34 + return err; 35 + }); 36 37 // SSE syntax: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format 38 return `event: playing\ndata: ${JSON.stringify(playing)}\n\n`;