Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Show timeout errors on the frontend (#2838)
Olga Bulatb94e60f4daf6
diff --git a/frontend/src/components/VErrorSection/VErrorSection.vue b/frontend/src/components/VErrorSection/VErrorSection.vueindex 42363862e..51edfcf52 100644--- a/frontend/src/components/VErrorSection/VErrorSection.vue+++ b/frontend/src/components/VErrorSection/VErrorSection.vue@@ -18,10 +18,9 @@<script lang="ts">import { computed, defineComponent, PropType } from "vue"-import { NO_RESULT, SERVER_TIMEOUT } from "~/constants/errors"-import { useSearchStore } from "~/stores/search"+import { ECONNABORTED, NO_RESULT, SERVER_TIMEOUT } from "~/constants/errors"-import type { NuxtError } from "@nuxt/types"+import type { FetchingError } from "~/types/fetch-state"export default defineComponent({components: {@@ -30,26 +29,25 @@ export default defineComponent({},props: {fetchingError: {- type: Object as PropType<NuxtError>,+ type: Object as PropType<FetchingError>,required: true,},},setup(props) {- const searchStore = useSearchStore()- const searchTerm = computed(() => searchStore.searchTerm)+ const searchTerm = computed(+ () => props.fetchingError.details?.searchTerm ?? ""+ )/*** The code used for the error page image.* For now, NO_RESULT image is used for searches without result,* and SERVER_TIMEOUT image is used as a fall-back for all other errors.*/- const errorCode = computed(() => {- return props.fetchingError?.message?.includes(NO_RESULT)- ? NO_RESULT- : SERVER_TIMEOUT- })+ const errorCode = computed(() =>+ props.fetchingError.code === NO_RESULT ? NO_RESULT : SERVER_TIMEOUT+ )const isTimeout = computed(() =>- props.fetchingError?.message?.toLowerCase().includes("timeout")+ [SERVER_TIMEOUT, ECONNABORTED].includes(props.fetchingError.code))return {diff --git a/frontend/src/components/VErrorSection/meta/VErrorSection.stories.mdx b/frontend/src/components/VErrorSection/meta/VErrorSection.stories.mdxindex 31215a7d1..ce5572b0b 100644--- a/frontend/src/components/VErrorSection/meta/VErrorSection.stories.mdx+++ b/frontend/src/components/VErrorSection/meta/VErrorSection.stories.mdx@@ -8,8 +8,7 @@ import {import VErrorSection from "~/components/VErrorSection/VErrorSection.vue"-import { NO_RESULT } from "~/constants/errors"-import { useSearchStore } from "@/stores/search"+import { ECONNABORTED, ERR_UNKNOWN, NO_RESULT } from "~/constants/errors"<Meta title="Components/VErrorSection" component={VErrorSection} />@@ -27,10 +26,6 @@ export const ErrorPageTemplate = (args) => ({template: `<VErrorSection v-bind="args" />`,components: { VErrorSection },setup() {- const searchStore = useSearchStore()- searchStore.setSearchTerm(- args.fetchingError.details?.searchTerm ?? "sad person"- )return { args }},})@@ -40,7 +35,7 @@ export const ErrorPageTemplate = (args) => ({name="No result"args={{fetchingError: {- message: NO_RESULT,+ code: NO_RESULT,requestKind: "search",searchType: "image",details: { searchTerm: "sad person" },@@ -60,7 +55,7 @@ This result appears when an API request times out.name="Server timeout"args={{fetchingError: {- message: "server timeout",+ code: ECONNABORTED,requestKind: "search",searchType: "image",},@@ -74,15 +69,17 @@ This result appears when an API request times out.This page is shown when there is some other error.-<Story- name="Unknown error"- args={{- fetchingError: {- message: "Unknown error",- requestKind: "search",- searchType: "image",- },- }}->- {ErrorPageTemplate.bind({})}-</Story>+<Canvas>+ <Story+ name="Unknown error"+ args={{+ fetchingError: {+ code: ERR_UNKNOWN,+ requestKind: "search",+ searchType: "image",+ },+ }}+ >+ {ErrorPageTemplate.bind({})}+ </Story>+</Canvas>diff --git a/frontend/src/components/VExternalSearch/VExternalSearchForm.vue b/frontend/src/components/VExternalSearch/VExternalSearchForm.vueindex 700810d29..d93d352f1 100644--- a/frontend/src/components/VExternalSearch/VExternalSearchForm.vue+++ b/frontend/src/components/VExternalSearch/VExternalSearchForm.vue@@ -96,7 +96,7 @@ export default defineComponent({},hasNoResults: {type: Boolean,- required: true,+ default: true,},},emits: {diff --git a/frontend/src/components/VFooter/VFooter.vue b/frontend/src/components/VFooter/VFooter.vueindex efb71ab9c..2edfdff8f 100644--- a/frontend/src/components/VFooter/VFooter.vue+++ b/frontend/src/components/VFooter/VFooter.vue@@ -147,7 +147,7 @@ export default defineComponent({/*We set the number of rows in JS to have 2 equally distributed link columns.*/- grid-template-rows: repeat(var(--link-col-height, 3), auto);+ grid-template-rows: repeat(var(--link-col-height, 4), auto);}.footer-lg .nav-list {diff --git a/frontend/src/components/VSearchResultsGrid/VAudioCollection.vue b/frontend/src/components/VSearchResultsGrid/VAudioCollection.vueindex 7c8d0064c..55c365eb5 100644--- a/frontend/src/components/VSearchResultsGrid/VAudioCollection.vue+++ b/frontend/src/components/VSearchResultsGrid/VAudioCollection.vue@@ -39,8 +39,6 @@ import VLoadMore from "~/components/VLoadMore.vue"import VGridSkeleton from "~/components/VSkeleton/VGridSkeleton.vue"import VSnackbar from "~/components/VSnackbar.vue"-import type { NuxtError } from "@nuxt/types"-/*** This component shows a loading skeleton if the results are not yet loaded,* and then shows the list of audio, with the Load more button if needed.@@ -66,7 +64,7 @@ export default defineComponent({required: true,},fetchState: {- type: Object as PropType<FetchState<NuxtError> | FetchState>,+ type: Object as PropType<FetchState>,required: true,},/**diff --git a/frontend/src/components/VSearchResultsGrid/VImageGrid.vue b/frontend/src/components/VSearchResultsGrid/VImageGrid.vueindex 4d24a918a..f2f90073f 100644--- a/frontend/src/components/VSearchResultsGrid/VImageGrid.vue+++ b/frontend/src/components/VSearchResultsGrid/VImageGrid.vue@@ -14,9 +14,6 @@:related-to="relatedTo"/></ol>- <h5 v-if="isError && !fetchState.isFinished" class="py-4">- {{ fetchState.fetchingError }}- </h5><footer v-if="!isSinglePage" class="pt-4"><VLoadMore /></footer>@@ -43,8 +40,6 @@ import VGridSkeleton from "~/components/VSkeleton/VGridSkeleton.vue"import VLoadMore from "~/components/VLoadMore.vue"import VImageCell from "~/components/VImageCell/VImageCell.vue"-import type { NuxtError } from "@nuxt/types"-export default defineComponent({name: "ImageGrid",components: { VGridSkeleton, VLoadMore, VImageCell },@@ -64,7 +59,7 @@ export default defineComponent({required: true,},fetchState: {- type: Object as PropType<FetchState | FetchState<NuxtError>>,+ type: Object as PropType<FetchState>,required: true,},imageGridLabel: {@@ -76,13 +71,12 @@ export default defineComponent({const searchStore = useSearchStore()const searchTerm = computed(() => searchStore.searchTerm)- const isError = computed(() => props.fetchState.fetchingError !== null)const relatedTo = computed(() => {return props.isSinglePage ? useRelatedMediaStore().mainMediaId : null})- return { isError, searchTerm, relatedTo }+ return { searchTerm, relatedTo }},})</script>diff --git a/frontend/src/constants/errors.ts b/frontend/src/constants/errors.tsindex 9b48069ac..7cf405795 100644--- a/frontend/src/constants/errors.ts+++ b/frontend/src/constants/errors.ts@@ -5,7 +5,45 @@export const NO_RESULT = "NO_RESULT"export const SERVER_TIMEOUT = "SERVER_TIMEOUT"+export const ECONNABORTED = "ECONNABORTED"-export const errorCodes = [NO_RESULT, SERVER_TIMEOUT] as const+export const ERR_UNKNOWN = "ERR_UNKNOWN"++export const customErrorCodes = [+ NO_RESULT,+ SERVER_TIMEOUT,+ ECONNABORTED,+ ERR_UNKNOWN,+] as const++/**+ * The error codes Axios uses.+ * @see https://github.com/axios/axios/blob/9588fcdec8aca45c3ba2f7968988a5d03f23168c/lib/core/AxiosError.js#L57C2-L71+ */+const axiosErrorCodes = [+ "ERR_BAD_OPTION_VALUE",+ "ERR_BAD_OPTION",+ "ECONNABORTED",+ "ETIMEDOUT",+ "ERR_NETWORK",+ "ERR_FR_TOO_MANY_REDIRECTS",+ "ERR_DEPRECATED",+ "ERR_BAD_RESPONSE",+ "ERR_BAD_REQUEST",+ "ERR_CANCELED",+ "ERR_NOT_SUPPORT",+ "ERR_INVALID_URL",+] as const++export const errorCodes = [...customErrorCodes, ...axiosErrorCodes] as const++export const clientSideErrorCodes: readonly ErrorCode[] = [+ ECONNABORTED,+ SERVER_TIMEOUT,+ NO_RESULT,+ ERR_UNKNOWN,+ "ERR_NETWORK",+ "ETIMEDOUT",+] as constexport type ErrorCode = (typeof errorCodes)[number]diff --git a/frontend/src/middleware/search.ts b/frontend/src/middleware/search.tsindex f0f2cd78c..93a19c545 100644--- a/frontend/src/middleware/search.ts+++ b/frontend/src/middleware/search.ts@@ -1,6 +1,7 @@import { useSearchStore } from "~/stores/search"import { useMediaStore } from "~/stores/media"-import { NO_RESULT } from "~/constants/errors"++import { handledClientSide } from "~/utils/errors"import type { Middleware } from "@nuxt/types"@@ -44,13 +45,7 @@ export const searchMiddleware: Middleware = async ({const results = await mediaStore.fetchMedia()const fetchingError = mediaStore.fetchState.fetchingError- // NO_RESULTS and timeout are handled client-side, for other errors show server error page- if (- !results &&- fetchingError &&- !fetchingError?.message?.includes(NO_RESULT) &&- !fetchingError?.message?.includes("timeout")- ) {+ if (!results && fetchingError && !handledClientSide(fetchingError)) {nuxtError(fetchingError)}}diff --git a/frontend/src/middleware/single-result.ts b/frontend/src/middleware/single-result.tsindex ca9f2f81b..83babf021 100644--- a/frontend/src/middleware/single-result.ts+++ b/frontend/src/middleware/single-result.ts@@ -1,6 +1,7 @@import { useSingleResultStore } from "~/stores/media/single-result"import { useSearchStore } from "~/stores/search"import { useRelatedMediaStore } from "~/stores/media/related-media"+import { isRetriable } from "~/utils/errors"import { AUDIO, IMAGE } from "~/constants/media"@@ -17,11 +18,15 @@ export const singleResultMiddleware: Middleware = async ({if (process.server) {const media = await singleResultStore.fetch(mediaType, route.params.id)- await useRelatedMediaStore($pinia).fetchMedia(mediaType, route.params.id)if (!media) {- error(singleResultStore.fetchState.fetchingError ?? {})+ const fetchingError = singleResultStore.fetchState.fetchingError++ if (fetchingError && !isRetriable(fetchingError)) {+ error(fetchingError ?? {})+ }}+ await useRelatedMediaStore($pinia).fetchMedia(mediaType, route.params.id)} else {// Client-side renderingsingleResultStore.setMediaById(mediaType, route.params.id)diff --git a/frontend/src/pages/audio/_id/index.vue b/frontend/src/pages/audio/_id/index.vueindex 28afd835b..8091a2b9d 100644--- a/frontend/src/pages/audio/_id/index.vue+++ b/frontend/src/pages/audio/_id/index.vue@@ -1,6 +1,11 @@<template><main :id="skipToContentTargetId" tabindex="-1" class="relative flex-grow">- <template v-if="audio">+ <VErrorSection+ v-if="fetchingError"+ :fetching-error="fetchingError"+ class="px-6 py-10 lg:px-10"+ />+ <template v-else-if="audio"><VSafetyWall v-if="isHidden" :media="audio" @reveal="reveal" /><template v-else><VSingleResultControls :media="audio" />@@ -33,7 +38,7 @@</template><script lang="ts">-import { ref } from "vue"+import { computed, ref } from "vue"import {defineComponent,useContext,@@ -83,6 +88,9 @@ export default defineComponent({const route = useRoute()const audio = ref<AudioDetail | null>(singleResultStore.audio)+ const fetchingError = computed(+ () => singleResultStore.fetchState.fetchingError+ )const { error: nuxtError } = useContext()@@ -121,6 +129,7 @@ export default defineComponent({return {audio,+ fetchingError,sendAudioEvent,diff --git a/frontend/src/pages/image/_id/index.vue b/frontend/src/pages/image/_id/index.vueindex 39a1a3bb9..2fd1ec933 100644--- a/frontend/src/pages/image/_id/index.vue+++ b/frontend/src/pages/image/_id/index.vue@@ -1,6 +1,11 @@<template><main :id="skipToContentTargetId" tabindex="-1" class="relative flex-grow">- <template v-if="image">+ <VErrorSection+ v-if="fetchingError"+ :fetching-error="fetchingError"+ class="px-6 py-10 lg:px-10"+ />+ <template v-else-if="image"><VSafetyWall v-if="isHidden" :media="image" @reveal="reveal" /><template v-else><VSingleResultControls :media="image" />@@ -114,6 +119,7 @@ import { useAnalytics } from "~/composables/use-analytics"import { useSensitiveMedia } from "~/composables/use-sensitive-media"import { useSingleResultPageMeta } from "~/composables/use-single-result-page-meta"+import { isRetriable } from "~/utils/errors"import { useSingleResultStore } from "~/stores/media/single-result"import { singleResultMiddleware } from "~/middleware/single-result"@@ -153,6 +159,9 @@ export default defineComponent({const route = useRoute()const image = ref<ImageDetail | null>(singleResultStore.image)+ const fetchingError = computed(+ () => singleResultStore.fetchState.fetchingError+ )/*** To make sure that image is loaded fast, we `src` to `image.thumbnail`,@@ -168,7 +177,9 @@ export default defineComponent({const imageId = route.value.params.idconst fetchedImage = await singleResultStore.fetch(IMAGE, imageId)if (!fetchedImage) {- nuxtError(singleResultStore.fetchState.fetchingError ?? {})+ if (fetchingError.value && !isRetriable(fetchingError.value)) {+ nuxtError(fetchingError.value)+ }} else {image.value = fetchedImageimageSrc.value = fetchedImage.thumbnail@@ -279,6 +290,7 @@ export default defineComponent({return {image,+ fetchingError,imageWidth,imageHeight,imageSrc,diff --git a/frontend/src/pages/search.vue b/frontend/src/pages/search.vueindex 9b599beec..7bbde4497 100644--- a/frontend/src/pages/search.vue+++ b/frontend/src/pages/search.vue@@ -58,12 +58,12 @@ import { searchMiddleware } from "~/middleware/search"import { useFeatureFlagStore } from "~/stores/feature-flag"import { useMediaStore } from "~/stores/media"import { useSearchStore } from "~/stores/search"-import { NO_RESULT } from "~/constants/errors"import { ALL_MEDIA, isSupportedMediaType } from "~/constants/media"import { skipToContentTargetId } from "~/constants/window"import { IsSidebarVisibleKey, ShowScrollButtonKey } from "~/types/provides"import { areQueriesEqual } from "~/utils/search-query-transform"+import { handledClientSide, isRetriable } from "~/utils/errors"import VErrorSection from "~/components/VErrorSection/VErrorSection.vue"import VScrollButton from "~/components/VScrollButton.vue"@@ -130,29 +130,23 @@ export default defineComponent({) => {/*** If the fetch has already started in the middleware,- * and there is an error or no results were found, don't re-fetch.+ * and there is an error status that will not change if retried, don't re-fetch.*/const shouldNotRefetch =- mediaStore.fetchState.fetchingError?.message &&- mediaStore.fetchState.hasStarted+ mediaStore.fetchState.hasStarted &&+ fetchingError.value !== null &&+ !isRetriable(fetchingError.value)if (shouldNotRefetch) return- const results = await mediaStore.fetchMedia(payload)- if (!results) {- const error = mediaStore.fetchState.fetchingError- /**- * NO_RESULT error is handled by the VErrorSection component in the child pages.- * For all other errors, show the Nuxt error page.- */- if (- error !== null &&- !error?.message?.toLowerCase().includes(NO_RESULT) &&- !error?.message?.toLowerCase().includes("timeout")- ) {- return nuxtError(error)- }+ await mediaStore.fetchMedia(payload)++ if (+ fetchingError.value === null ||+ handledClientSide(fetchingError.value)+ ) {+ return null}- return null+ return nuxtError(fetchingError.value)}const fetchingError = computed(() => mediaStore.fetchState.fetchingError)diff --git a/frontend/src/pages/search/audio.vue b/frontend/src/pages/search/audio.vueindex 0a5a15f83..6dd9d23fc 100644--- a/frontend/src/pages/search/audio.vue+++ b/frontend/src/pages/search/audio.vue@@ -17,8 +17,6 @@ import type { FetchState } from "~/types/fetch-state"import VAudioCollection from "~/components/VSearchResultsGrid/VAudioCollection.vue"-import type { NuxtError } from "@nuxt/types"-export default defineComponent({name: "AudioSearch",components: {@@ -30,7 +28,7 @@ export default defineComponent({required: true,},fetchState: {- type: Object as PropType<FetchState<NuxtError> | FetchState>,+ type: Object as PropType<FetchState>,required: true,},},diff --git a/frontend/src/pages/search/image.vue b/frontend/src/pages/search/image.vueindex 8259cd8cd..def157393 100644--- a/frontend/src/pages/search/image.vue+++ b/frontend/src/pages/search/image.vue@@ -17,8 +17,6 @@ import type { FetchState } from "~/types/fetch-state"import VImageGrid from "~/components/VSearchResultsGrid/VImageGrid.vue"-import type { NuxtError } from "@nuxt/types"-export default defineComponent({name: "ImageSearch",components: { VImageGrid },@@ -28,7 +26,7 @@ export default defineComponent({required: true,},fetchState: {- type: Object as PropType<FetchState<NuxtError> | FetchState>,+ type: Object as PropType<FetchState>,required: true,},searchTerm: {diff --git a/frontend/src/stores/media/index.ts b/frontend/src/stores/media/index.tsindex 2cbbb1267..8ae023eee 100644--- a/frontend/src/stores/media/index.ts+++ b/frontend/src/stores/media/index.ts@@ -1,9 +1,8 @@import { defineStore } from "pinia"-import axios from "axios"-import { warn } from "~/utils/console"import { hash, rand as prng } from "~/utils/prng"+import { isRetriable, parseFetchingError } from "~/utils/errors"import prepareSearchQueryParams from "~/utils/prepare-search-query-params"import type {AudioDetail,@@ -11,7 +10,7 @@ import type {ImageDetail,Media,} from "~/types/media"-import type { FetchState } from "~/types/fetch-state"+import type { FetchingError, FetchState } from "~/types/fetch-state"import {ALL_MEDIA,AUDIO,@@ -26,8 +25,6 @@ import { isSearchTypeSupported, useSearchStore } from "~/stores/search"import { useRelatedMediaStore } from "~/stores/media/related-media"import { deepFreeze } from "~/utils/deep-freeze"-import type { NuxtError } from "@nuxt/types"-export type MediaStoreResult = {count: numberpageCount: number@@ -41,11 +38,14 @@ export interface MediaState {image: MediaStoreResult}mediaFetchState: {- audio: FetchState<NuxtError>- image: FetchState<NuxtError>+ audio: FetchState+ image: FetchState}currentPage: number}+export type MediaResults = {+ [MT in SupportedMediaType]: DetailFromMediaType<MT>[]+}export const initialResults = deepFreeze({count: 0,@@ -103,13 +103,13 @@ export const useMediaStore = defineStore("media", {/*** Returns object with a key for each supported media type and arrays of media items for each.*/- resultItems(state) {+ resultItems(state): MediaResults {return supportedMediaTypes.reduce((items, type) => ({...items,[type]: Object.values(state.results[type].items),}),- {} as Record<SupportedMediaType, Media[]>+ {} as MediaResults)},@@ -142,12 +142,12 @@ export const useMediaStore = defineStore("media", {* Search fetching state for selected search type. For 'All content', aggregates* the values for supported media types.*/- fetchState(): FetchState<NuxtError> {+ fetchState(): FetchState {if (this._searchType === ALL_MEDIA) {/*** For all_media, we return 'All media fetching error' if all types have some kind of error.*/- const atLeastOne = (property: keyof FetchState<NuxtError>) =>+ const atLeastOne = (property: keyof FetchState) =>supportedMediaTypes.some((type) => this.mediaFetchState[type][property])@@ -164,7 +164,7 @@ export const useMediaStore = defineStore("media", {* The handling of errors other than 429 should be improved after we* get more information about the error codes we get from the API.*/- const allMediaError = (): null | NuxtError => {+ const allMediaError = (): null | FetchingError => {const errors = getMediaErrors(this.mediaFetchState)if (!errors.length) {@@ -172,7 +172,8 @@ export const useMediaStore = defineStore("media", {}const tooManyRequestsError = findTooManyRequestsError(errors)- if (tooManyRequestsError) {+ if (tooManyRequestsError !== null) {+ tooManyRequestsError["searchType"] = ALL_MEDIAreturn tooManyRequestsError}@@ -181,9 +182,7 @@ export const useMediaStore = defineStore("media", {return noResultError}// Temporarily return the first error, until we have a better way to handle this.- const results = errors.filter(- (error) => !error.message?.includes(NO_RESULT)- )+ const results = errors.filter((error) => error.code !== NO_RESULT)return results.length ? results[0] : null}@@ -251,7 +250,7 @@ export const useMediaStore = defineStore("media", {.sort(([, a], [, b]) => b - a)[0]// First, set the results to the type with most hits...- const newResults = media[mostHits]+ const newResults = media[mostHits] as (AudioDetail | ImageDetail)[]// ...then push other items into the list, using a random index.let nonImageIndex = 1@@ -298,12 +297,12 @@ export const useMediaStore = defineStore("media", {* @param mediaType - The media type for which the request was made.* @param error - The string representation of the error, if any.*/- _endFetching(mediaType: SupportedMediaType, error?: NuxtError) {+ _endFetching(mediaType: SupportedMediaType, error?: FetchingError) {this.mediaFetchState[mediaType].fetchingError = error || nullthis.mediaFetchState[mediaType].hasStarted = truethis.mediaFetchState[mediaType].isFetching = false- if (error) {+ if (error && !isRetriable(error)) {this.mediaFetchState[mediaType].isFinished = true}},@@ -329,7 +328,7 @@ export const useMediaStore = defineStore("media", {_updateFetchState(mediaType: SupportedMediaType,action: "reset" | "start" | "end" | "finish",- error?: NuxtError+ error?: FetchingError) {switch (action) {case "reset":@@ -462,7 +461,7 @@ export const useMediaStore = defineStore("media", {const service = initServices[mediaType](accessToken)const data = await service.search(queryParams)const mediaCount = data.result_count- let errorData: NuxtError | undefined+ let errorData: FetchingError | undefined/*** When there are no results for a query, the API returns a 200 response.* In such cases, we show the "No results" client error page.@@ -470,7 +469,11 @@ export const useMediaStore = defineStore("media", {if (!mediaCount) {page = 0errorData = {- message: `${NO_RESULT}: ${mediaType}.`,+ message: `No results found for ${queryParams.q}`,+ code: NO_RESULT,+ requestKind: "search",+ searchType: mediaType,+ details: { searchTerm: queryParams.q ?? "" },}}this._updateFetchState(mediaType, "end", errorData)@@ -485,14 +488,14 @@ export const useMediaStore = defineStore("media", {})return mediaCount} catch (error: unknown) {- const nuxtErrorData = getNuxtErrorData(error, mediaType)- this._updateFetchState(mediaType, "end", nuxtErrorData)+ const errorData = parseFetchingError(error, mediaType, "search", {+ searchTerm: queryParams.q ?? "",+ })++ this._updateFetchState(mediaType, "end", errorData)this.$nuxt.$sentry.captureException(error, {- extra: {- nuxtErrorData,- mediaType,- },+ extra: { errorData },})return null}@@ -515,53 +518,19 @@ export const useMediaStore = defineStore("media", {},})-export const getNuxtErrorData = (- error: unknown,- mediaType: SupportedMediaType-): NuxtError => {- const errorData = {- message: `Error fetching ${mediaType} results. `,- } as NuxtError-- if (axios.isAxiosError(error)) {- // If the error is an axios error:- // Received a response not in the 2xx range.- if (error.response) {- errorData.message += `Request failed with status code: ${error.response.status}`- errorData.statusCode = error.response.status- } else if (error.request) {- // The request was sent, but the response was never received.- if (error.code === "ECONNABORTED") {- errorData.message += `Timeout error`- } else {- errorData.message += `No response received from the server`- }- } else {- // Something happened during the request setup.- errorData.message += `Unknown Axios error`- }- } else {- // Unknown error, not from axios.- errorData.message += `Unknown error`- }- return errorData-}--const getMediaErrors = (- mediaFetchStates: MediaState["mediaFetchState"]-): NuxtError[] => {+const getMediaErrors = (mediaFetchStates: MediaState["mediaFetchState"]) => {return supportedMediaTypes.map((mediaType) => mediaFetchStates[mediaType].fetchingError)- .filter(Boolean) as NuxtError[]+ .filter((err): err is FetchingError => err !== null)}-const findTooManyRequestsError = (errors: NuxtError[]): null | NuxtError => {+const findTooManyRequestsError = (errors: FetchingError[]) => {return errors.find(({ statusCode }) => statusCode === 429) ?? null}-const findNoResultError = (errors: NuxtError[]): null | NuxtError => {+const findNoResultError = (errors: FetchingError[]): FetchingError | null => {return errors.length === supportedMediaTypes.length &&- errors.every(({ message }) => message?.includes(NO_RESULT))- ? { message: `${NO_RESULT}: All media` }+ errors.every(({ code }) => code === NO_RESULT)+ ? { ...errors[0], searchType: ALL_MEDIA }: null}diff --git a/frontend/src/stores/media/related-media.ts b/frontend/src/stores/media/related-media.tsindex 09fc54225..eed57e08e 100644--- a/frontend/src/stores/media/related-media.ts+++ b/frontend/src/stores/media/related-media.ts@@ -1,17 +1,16 @@import { defineStore } from "pinia"-import axios from "axios"+import { parseFetchingError } from "~/utils/errors"import { initServices } from "~/stores/media/services"-import type { FetchState } from "~/types/fetch-state"++import type { FetchingError, FetchState } from "~/types/fetch-state"import type { Media } from "~/types/media"import type { SupportedMediaType } from "~/constants/media"-import type { NuxtError } from "@nuxt/types"-interface RelatedMediaState {mainMediaId: null | stringmedia: Media[]- fetchState: FetchState<NuxtError>+ fetchState: FetchState}export const useRelatedMediaStore = defineStore("related-media", {@@ -29,7 +28,7 @@ export const useRelatedMediaStore = defineStore("related-media", {},actions: {- _endFetching(error?: NuxtError) {+ _endFetching(error?: FetchingError) {this.fetchState.fetchingError = error || nullthis.fetchState.hasStarted = truethis.fetchState.isFetching = false@@ -60,13 +59,12 @@ export const useRelatedMediaStore = defineStore("related-media", {return this.media.length} catch (error) {- const message = `Could not fetch related ${mediaType} for id ${id}.`- const statusCode =- axios.isAxiosError(error) && error.response?.status- ? error.response.status- : 404- this._endFetching({ message, statusCode })- this.$nuxt.$sentry.captureException(error)+ const errorData = parseFetchingError(error, mediaType, "related", {+ id,+ })++ this._endFetching(errorData)+ this.$nuxt.$sentry.captureException(error, { extra: { errorData } })return null}},diff --git a/frontend/src/stores/media/single-result.ts b/frontend/src/stores/media/single-result.tsindex 9be4c32c9..c4971a901 100644--- a/frontend/src/stores/media/single-result.ts+++ b/frontend/src/stores/media/single-result.ts@@ -1,8 +1,5 @@import { defineStore } from "pinia"-import axios from "axios"--import type { FetchState } from "~/types/fetch-state"import type {AudioDetail,DetailFromMediaType,@@ -15,15 +12,15 @@ import type { SupportedMediaType } from "~/constants/media"import { initServices } from "~/stores/media/services"import { useMediaStore } from "~/stores/media/index"import { useProviderStore } from "~/stores/provider"-import { log } from "~/utils/console"+import { parseFetchingError } from "~/utils/errors"-import type { NuxtError } from "@nuxt/types"+import type { FetchingError, FetchState } from "~/types/fetch-state"export type MediaItemState = {mediaType: SupportedMediaType | nullmediaId: string | nullmediaItem: DetailFromMediaType<SupportedMediaType> | null- fetchState: FetchState<NuxtError>+ fetchState: FetchState}export const useSingleResultStore = defineStore("single-result", {@@ -50,7 +47,7 @@ export const useSingleResultStore = defineStore("single-result", {},actions: {- _endFetching(error?: NuxtError) {+ _endFetching(error?: FetchingError) {this.fetchState.isFetching = falsethis.fetchState.fetchingError = error || null},@@ -59,7 +56,7 @@ export const useSingleResultStore = defineStore("single-result", {this.fetchState.fetchingError = null},- _updateFetchState(action: "start" | "end", option?: NuxtError) {+ _updateFetchState(action: "start" | "end", option?: FetchingError) {action === "start" ? this._startFetching() : this._endFetching(option)},@@ -169,22 +166,13 @@ export const useSingleResultStore = defineStore("single-result", {return item as DetailFromMediaType<MediaType>} catch (error) {- this.reset()- const statusCode = getErrorStatusCode(error)- const message = `Error fetching single ${type} item with id ${id}`-- this._updateFetchState("end", { statusCode, message })-- log(`${message}. Sending error to Sentry: ${JSON.stringify(error)}`)- this.$nuxt.$sentry.captureException(error)-+ const errorData = parseFetchingError(error, type, "single-result", {+ id,+ })+ this._updateFetchState("end", errorData)+ this.$nuxt.$sentry.captureException(error, { extra: { errorData } })return null}},},})--const getErrorStatusCode = (error: unknown) =>- axios.isAxiosError(error) && error.response?.status- ? error.response.status- : 404diff --git a/frontend/src/stores/provider.ts b/frontend/src/stores/provider.tsindex 4e2c6ac60..7cd9970c6 100644--- a/frontend/src/stores/provider.ts+++ b/frontend/src/stores/provider.ts@@ -1,20 +1,19 @@import { capital } from "case"import { defineStore } from "pinia"import { ssrRef } from "@nuxtjs/composition-api"-import axios from "axios"import { env } from "~/utils/env"+import { parseFetchingError } from "~/utils/errors"import {AUDIO,IMAGE,SupportedMediaType,supportedMediaTypes,} from "~/constants/media"-import { warn } from "~/utils/console"import { initProviderServices } from "~/data/media-provider-service"import type { MediaProvider } from "~/types/media-provider"-import type { FetchState } from "~/types/fetch-state"+import type { FetchingError, FetchState } from "~/types/fetch-state"import type { Ref } from "vue"@@ -60,7 +59,7 @@ export const useProviderStore = defineStore("provider", {}),actions: {- _endFetching(mediaType: SupportedMediaType, error?: string) {+ _endFetching(mediaType: SupportedMediaType, error?: FetchingError) {this.fetchState[mediaType].fetchingError = error || nullif (error) {this.fetchState[mediaType].isFinished = true@@ -78,7 +77,7 @@ export const useProviderStore = defineStore("provider", {_updateFetchState(mediaType: SupportedMediaType,action: "start" | "end",- option?: string+ option?: FetchingError) {action === "start"? this._startFetching(mediaType)@@ -146,16 +145,12 @@ export const useProviderStore = defineStore("provider", {sortedProviders = sortProviders(res.data)this._updateFetchState(mediaType, "end")} catch (error: unknown) {- let errorMessage = `There was an error fetching media providers for ${mediaType}`- if (error instanceof Error) {- errorMessage = axios.isAxiosError(error)- ? `${errorMessage}: ${error.code}`- : `${errorMessage}: ${error.message}`- }- warn(errorMessage)+ const errorData = parseFetchingError(error, mediaType, "provider")+// Fallback on existing providers if there was an errorsortedProviders = this.providers[mediaType]- this._updateFetchState(mediaType, "end", errorMessage)+ this._updateFetchState(mediaType, "end", errorData)+ this.$nuxt.$sentry.captureException(error, { extra: { errorData } })} finally {this.providers[mediaType] = sortedProviders}diff --git a/frontend/src/types/fetch-state.ts b/frontend/src/types/fetch-state.tsindex c16579cf4..f674b7101 100644--- a/frontend/src/types/fetch-state.ts+++ b/frontend/src/types/fetch-state.ts@@ -1,9 +1,34 @@-export interface BaseFetchState {+import type { ErrorCode } from "~/constants/errors"+import type { SupportedSearchType } from "~/constants/media"++import type { NuxtError } from "@nuxt/types"++/**+ * Describes the kind of API request that was made.+ */+export type RequestKind = "search" | "single-result" | "related" | "provider"++/**+ * This interface represents errors related to data-fetching from the API.+ * It has the information that can be used on the error page.+ */+export interface FetchingError extends NuxtError {+ /**+ * Axios error codes or custom error code like NO_RESULT.+ * @see frontend/src/constants/errors.ts+ */+ code: ErrorCode+ requestKind: RequestKind+ searchType: SupportedSearchType+ /**+ * Additional details about the error, e.g. the search term.+ */+ details?: Record<string, string>+}++export interface FetchState {isFetching: booleanhasStarted?: booleanisFinished?: boolean-}--export interface FetchState<ErrorType = string> extends BaseFetchState {- fetchingError: null | ErrorType+ fetchingError: FetchingError | null}diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.tsnew file mode 100644index 000000000..64e3aa5a3--- /dev/null+++ b/frontend/src/utils/errors.ts@@ -0,0 +1,88 @@+import axios from "axios"++import {+ clientSideErrorCodes,+ ERR_UNKNOWN,+ ErrorCode,+ errorCodes,+ NO_RESULT,+} from "~/constants/errors"+import type { FetchingError, RequestKind } from "~/types/fetch-state"+import type { SupportedSearchType } from "~/constants/media"++/**+ * Parses an error object to standardize error-related details for the frontend.+ * @param error - the error object to parse.+ * @param searchType - the type of media that request was made for (can be `all content`).+ * @param requestKind - the kind of request that was made.+ * @param details - additional data to display on the error page, e.g. searchTerm.+ */+export const parseFetchingError = (+ error: unknown,+ searchType: SupportedSearchType,+ requestKind: RequestKind,+ details?: Record<string, string>+) => {+ const fetchingError: FetchingError = {+ requestKind,+ details,+ searchType,+ code: ERR_UNKNOWN,+ }++ if (axios.isAxiosError(error)) {+ if (isValidErrorCode(error.code)) {+ fetchingError.code = error.code+ }+ if (error.response?.status) {+ fetchingError.statusCode = error.response.status+ }+ const responseData = error?.response?.data+ // Use the message returned by the API.+ if (+ typeof responseData === "object" &&+ responseData !== null &&+ "detail" in responseData+ ) {+ fetchingError.message = responseData?.detail as string+ } else {+ fetchingError.message = error.message+ }+ } else {+ fetchingError.message = (error as Error).message+ }+ return fetchingError+}++const NON_RETRYABLE_ERROR_CODES = [429, 500, 404] as const+const isNonRetryableErrorStatusCode = (statusCode: number | undefined) => {+ return (+ statusCode &&+ (NON_RETRYABLE_ERROR_CODES as readonly number[]).includes(statusCode)+ )+}++const isValidErrorCode = (+ code: string | undefined | null+): code is ErrorCode => {+ if (!code) return false+ return (errorCodes as readonly string[]).includes(code)+}++/**+ * Returns true if the request should be retried if error occurred on+ * the server. For 429, 500 or 404 errors, or for NO_RESULT error,+ * the status will not change on retry, so the request should not be resent.+ * TODO: Update this function with other error codes if needed.+ */+export const isRetriable = (error: FetchingError) => {+ const { statusCode, code } = error+ return !(isNonRetryableErrorStatusCode(statusCode) || code === NO_RESULT)+}++export const handledClientSide = (error: FetchingError) => {+ return (+ !isNonRetryableErrorStatusCode(error.statusCode) &&+ (clientSideErrorCodes as readonly string[]).includes(error.code)+ )+}diff --git a/frontend/test/unit/specs/stores/media-store.spec.js b/frontend/test/unit/specs/stores/media-store.spec.jsindex bd1c7040d..1e612faa3 100644--- a/frontend/test/unit/specs/stores/media-store.spec.js+++ b/frontend/test/unit/specs/stores/media-store.spec.js@@ -1,10 +1,8 @@-import { AxiosError } from "axios"-import { setActivePinia, createPinia } from "~~/test/unit/test-utils/pinia"import { deepClone } from "~/utils/clone"-import { initialResults, useMediaStore, getNuxtErrorData } from "~/stores/media"+import { initialResults, useMediaStore } from "~/stores/media"import { useSearchStore } from "~/stores/search"import { ALL_MEDIA, AUDIO, IMAGE, supportedMediaTypes } from "~/constants/media"@@ -173,8 +171,8 @@ describe("Media Store", () => {it.each`searchType | fetchState- ${ALL_MEDIA} | ${{ fetchingError: "Error", hasStarted: true, isFetching: true, isFinished: false }}- ${AUDIO} | ${{ fetchingError: "Error", hasStarted: true, isFetching: false, isFinished: true }}+ ${ALL_MEDIA} | ${{ fetchingError: { requestKind: "search", statusCode: 429, searchType: ALL_MEDIA }, hasStarted: true, isFetching: true, isFinished: false }}+ ${AUDIO} | ${{ fetchingError: { requestKind: "search", statusCode: 429, searchType: AUDIO }, hasStarted: true, isFetching: false, isFinished: true }}${IMAGE} | ${{ fetchingError: null, hasStarted: true, isFetching: true, isFinished: false }}`("fetchState for $searchType returns $fetchState",@@ -182,7 +180,11 @@ describe("Media Store", () => {const mediaStore = useMediaStore()const searchStore = useSearchStore()searchStore.setSearchType(searchType)- mediaStore._updateFetchState(AUDIO, "end", "Error")+ mediaStore._updateFetchState(AUDIO, "end", {+ requestKind: "search",+ statusCode: 429,+ searchType: AUDIO,+ })mediaStore._updateFetchState(IMAGE, "start")expect(mediaStore.fetchState).toEqual(fetchState)@@ -199,12 +201,16 @@ describe("Media Store", () => {mediaStore._updateFetchState(IMAGE, "end", {message: "Error",statusCode: 500,+ requestKind: "search",+ searchType: IMAGE,})expect(mediaStore.fetchState).toEqual({fetchingError: {message: "Error",statusCode: 500,+ requestKind: "search",+ searchType: IMAGE,},hasStarted: true,isFetching: false,@@ -336,7 +342,11 @@ describe("Media Store", () => {})expect(mediaStore.mediaFetchState["image"].fetchingError).toEqual({- message: "NO_RESULT: image.",+ code: "NO_RESULT",+ details: { searchTerm: "cat" },+ message: "No results found for cat",+ requestKind: "search",+ searchType: "image",})})@@ -422,51 +432,4 @@ describe("Media Store", () => {})})})-- // Add a test for getNuxtErrorData- describe("getNuxtErrorData", () => {- it.each`- status | message- ${500} | ${"Internal server error"}- ${429} | ${"Too many requests"}- `(- "returns the correct error data for axios errors",- ({ status, message }) => {- const error = new AxiosError(- "",- "ERR_BAD_RESPONSE",- {},- {},- {- status,- data: { detail: message },- }- )- const expectedErrorData = {- statusCode: status,- message: `Error fetching image results. Request failed with status code: ${status}`,- }- const actualErrorData = getNuxtErrorData(error, IMAGE)- expect(actualErrorData).toEqual(expectedErrorData)- }- )-- it("returns the correct error data for Axios error without a response", () => {- const error = new AxiosError("", "ERR_BAD_REQUEST", {}, {})- const expectedErrorData = {- message:- "Error fetching image results. No response received from the server",- }- const actualErrorData = getNuxtErrorData(error, IMAGE)- expect(actualErrorData).toEqual(expectedErrorData)- })- it("returns the correct error data for non-Axios errors", () => {- const error = new Error("Some error")- const expectedErrorData = {- message: "Error fetching image results. Unknown error",- }- const actualErrorData = getNuxtErrorData(error, IMAGE)- expect(actualErrorData).toEqual(expectedErrorData)- })- })})diff --git a/frontend/test/unit/specs/stores/provider.spec.js b/frontend/test/unit/specs/stores/provider.spec.jsindex 60c36e23f..035851e07 100644--- a/frontend/test/unit/specs/stores/provider.spec.js+++ b/frontend/test/unit/specs/stores/provider.spec.js@@ -1,3 +1,5 @@+import { AxiosError } from "axios"+import { setActivePinia, createPinia } from "~~/test/unit/test-utils/pinia"import { warn } from "~/utils/console"@@ -6,10 +8,6 @@ import { useSearchStore } from "~/stores/search"import { useProviderStore } from "~/stores/provider"import { initProviderServices } from "~/data/media-provider-service"-jest.mock("axios", () => ({- ...jest.requireActual("axios"),- isAxiosError: jest.fn((obj) => "response" in obj),-}))jest.mock("@nuxtjs/composition-api", () => ({ssrRef: (v) => jest.fn(v),}))@@ -108,17 +106,35 @@ describe("Provider Store", () => {it("fetchMediaProviders on error", async () => {for (const mediaType of supportedMediaTypes) {initProviderServices[mediaType] = () => ({- getProviderStats: jest- .fn()- .mockImplementation(() => Promise.reject(new Error("Not found"))),+ getProviderStats: jest.fn().mockImplementation(() =>+ Promise.reject(+ new AxiosError(+ "Not found",+ AxiosError.ERR_BAD_REQUEST,+ {},+ {},+ {+ data: { detail: "Not found" },+ status: 404,+ statusText: "Not found",+ headers: {},+ config: {},+ }+ )+ )+ ),})}const searchStore = useSearchStore()await providerStore.fetchMediaProviders()for (const mediaType of supportedMediaTypes) {- expect(providerStore.fetchState[mediaType].fetchingError).toEqual(- `There was an error fetching media providers for ${mediaType}: Not found`- )+ expect(providerStore.fetchState[mediaType].fetchingError).toEqual({+ code: AxiosError.ERR_BAD_REQUEST,+ message: "Not found",+ requestKind: "provider",+ searchType: mediaType,+ statusCode: 404,+ })expect(providerStore.providers[mediaType]).toEqual([])expect(searchStore.filters[`${mediaType}Providers`]).toEqual([])}diff --git a/frontend/test/unit/specs/stores/single-result-store.spec.js b/frontend/test/unit/specs/stores/single-result-store.spec.jsindex a573c9d4a..79dcde3c2 100644--- a/frontend/test/unit/specs/stores/single-result-store.spec.js+++ b/frontend/test/unit/specs/stores/single-result-store.spec.js@@ -1,3 +1,5 @@+import { AxiosError } from "axios"+import { createPinia, setActivePinia } from "~~/test/unit/test-utils/pinia"import { getAudioObj } from "~~/test/unit/fixtures/audio"@@ -170,8 +172,11 @@ describe("Media Item Store", () => {Promise.reject(new Error(errorMessage)))const expectedError = {- message: `Error fetching single ${type} item with id foo`,- statusCode: 404,+ message: "error",+ code: "ERR_UNKNOWN",+ details: { id: "foo" },+ requestKind: "single-result",+ searchType: type,}await singleResultStore.fetchMediaItem(type, "foo")@@ -185,14 +190,30 @@ describe("Media Item Store", () => {it.each(supportedMediaTypes)("fetchMediaItem on 404 sets fetchingError and throws a new error",async (type) => {- const errorResponse = { response: { status: 404 } }+ const errorResponse = new AxiosError(+ "Not found",+ AxiosError.ERR_BAD_REQUEST,+ {},+ {},+ {+ data: {},+ status: 404,+ statusText: "Not found",+ headers: {},+ config: {},+ }+ )mocks[type].mockImplementationOnce(() => Promise.reject(errorResponse))const id = "foo"const expectedError = {- message: `Error fetching single ${type} item with id ${id}`,+ message: "Not found",statusCode: errorResponse.response.status,+ code: errorResponse.code,+ requestKind: "single-result",+ searchType: type,+ details: { id },}expect(await singleResultStore.fetch(type, id)).toEqual(null)expect(singleResultStore.fetchState.fetchingError).toEqual(