chore: improve error handling in frontend (#5109)

This commit is contained in:
Jérémie Pardou authored and GitHub committed 2026-05-13 19:36:30 +00:00
1 parent d6c8c8b4b0
commit 2daacc7bea
39 files changed
+565 -192

No files matched your search

+1
View File
@@ -182,6 +182,7 @@ DATABASE_NAME=baserow
# BASEROW_TOTP_ISSUER_NAME=
# Set SENTRY_DSN to `fake` if you want to test sentry logging without sentry itself
# SENTRY_DSN=
# SENTRY_BACKEND_DSN=
@@ -1439,10 +1439,12 @@ SENTRY_DSN = SENTRY_BACKEND_DSN or os.getenv("SENTRY_DSN")
if SENTRY_DSN:
import sentry_sdk
import sentry_sdk.integrations as _sentry_integrations
from loguru import logger
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.scrubber import DEFAULT_DENYLIST, EventScrubber
from baserow.core.sentry import (
ConsoleSentryTransport,
drop_expected_asyncio_websocket_ping_timeout_events,
)
@@ -1457,6 +1459,15 @@ if SENTRY_DSN:
]
SENTRY_DENYLIST = DEFAULT_DENYLIST + ["username", "email", "name"]
sentry_transport = None
if SENTRY_DSN == "fake":
logger.info(
"[SENTRY] Using fake backend Sentry DSN, events will be logged to the "
"console."
)
SENTRY_DSN = "https://public@example.invalid/1"
sentry_transport = ConsoleSentryTransport()
sentry_sdk.init(
dsn=SENTRY_DSN,
@@ -1465,6 +1476,7 @@ if SENTRY_DSN:
before_send=drop_expected_asyncio_websocket_ping_timeout_events,
event_scrubber=EventScrubber(recursive=True, denylist=SENTRY_DENYLIST),
environment=os.getenv("SENTRY_ENVIRONMENT", ""),
transport=sentry_transport,
)
else:
BASEROW_LAZY_LOADED_LIBRARIES.append("sentry_sdk")
+59
View File
@@ -1,8 +1,67 @@
import json
import logging
from typing import Any
from django.contrib.auth import get_user_model
from loguru import logger
from sentry_sdk.transport import Transport
SENTRY_LOG_PREFIX = "[SENTRY]"
def _get_sentry_event_message(event: dict[str, Any]) -> str:
exception_values = event.get("exception", {}).get("values", [])
if exception_values:
exception = exception_values[-1]
exception_type = exception.get("type", "UnknownError")
exception_value = exception.get("value", "")
if exception_value:
return f"{exception_type}: {exception_value}"
return exception_type
log_entry = event.get("logentry", {})
if log_entry.get("formatted"):
return log_entry["formatted"]
if log_entry.get("message"):
return log_entry["message"]
if event.get("message"):
return str(event["message"])
return "Sentry event captured without a message."
def log_sentry_event_to_console(event: dict[str, Any]) -> None:
level = str(event.get("level", "error")).upper()
event_id = event.get("event_id", "unknown")
message = _get_sentry_event_message(event)
logger.error(f"{SENTRY_LOG_PREFIX} [{level}] [{event_id}] {message}")
class ConsoleSentryTransport(Transport):
"""
A transport that logs Sentry events locally instead of sending them to Sentry.
"""
def capture_event(self, event):
log_sentry_event_to_console(event)
def capture_envelope(self, envelope):
for item in envelope.items:
item_type = item.headers.get("type", "unknown")
payload = item.get_bytes().decode("utf-8", errors="replace")
if item_type == "event":
try:
log_sentry_event_to_console(json.loads(payload))
continue
except json.JSONDecodeError:
pass
logger.error(
f"{SENTRY_LOG_PREFIX} [ENVELOPE] [{item_type.upper()}] {payload}"
)
def drop_expected_asyncio_websocket_ping_timeout_events(
event: dict[str, Any], hint: dict[str, Any]
+42 -1
View File
@@ -1,6 +1,13 @@
import logging
from unittest.mock import patch
from baserow.core.sentry import drop_expected_asyncio_websocket_ping_timeout_events
from sentry_sdk.envelope import Envelope
from baserow.core.sentry import (
ConsoleSentryTransport,
drop_expected_asyncio_websocket_ping_timeout_events,
log_sentry_event_to_console,
)
def test_drop_expected_asyncio_websocket_ping_timeout_events():
@@ -44,3 +51,37 @@ def test_drop_expected_asyncio_websocket_ping_timeout_events_keeps_other_errors(
)
== event
)
@patch("baserow.core.sentry.logger")
def test_log_sentry_event_to_console_logs_exception_with_prefix(mock_logger):
log_sentry_event_to_console(
{
"event_id": "event-123",
"level": "error",
"exception": {
"values": [
{
"type": "ValueError",
"value": "broken",
}
]
},
}
)
mock_logger.error.assert_called_once_with(
"[SENTRY] [ERROR] [event-123] ValueError: broken"
)
@patch("baserow.core.sentry.logger")
def test_console_sentry_transport_logs_envelope_payload(mock_logger):
envelope = Envelope(headers={"event_id": "event-123"})
envelope.add_event({"event_id": "event-123", "message": "Envelope event"})
ConsoleSentryTransport().capture_envelope(envelope)
mock_logger.error.assert_called_once_with(
"[SENTRY] [ERROR] [event-123] Envelope event"
)
@@ -0,0 +1,9 @@
{
"type": "refactor",
"message": "Improve error handling in frontend",
"issue_origin": "github",
"issue_number": null,
"domain": "core",
"bullet_points": [],
"created_at": "2026-04-16"
}
@@ -44,10 +44,21 @@ if (!$hasFeature(EnterpriseFeatures.DATA_SCANNER)) {
throw createError({
statusCode: 401,
message: 'Available in the enterprise version',
data: {
report: false,
},
fatal: true,
})
}
if (!store.getters['auth/isStaff']) {
throw createError({ statusCode: 403, message: 'Forbidden.' })
throw createError({
statusCode: 403,
message: 'Forbidden.',
data: {
report: false,
},
fatal: true,
})
}
</script>
@@ -161,6 +161,10 @@ if (workspaceId) {
throw createError({
statusCode: 401,
message: 'Available in the advanced/enterprise version',
data: {
report: false,
},
fatal: true,
})
} else if (
!$hasPermission(
@@ -169,15 +173,33 @@ if (workspaceId) {
workspaceId
)
) {
throw createError({ statusCode: 404, message: 'Page not found' })
throw createError({
statusCode: 404,
message: 'Page not found',
data: {
report: false,
},
fatal: true,
})
}
} else if (!$hasFeature(EnterpriseFeatures.AUDIT_LOG)) {
throw createError({
statusCode: 401,
message: 'Available in the advanced/enterprise version',
data: {
report: false,
},
fatal: true,
})
} else if (!store.getters['auth/isStaff']) {
throw createError({ statusCode: 403, message: 'Forbidden.' })
throw createError({
statusCode: 403,
message: 'Forbidden.',
data: {
report: false,
},
fatal: true,
})
}
// Template refs
@@ -224,10 +224,23 @@ const { data, error } = await useAsyncData(
route.params.id
)
return licenseData
} catch {
} catch (e) {
const statusCode = e.response?.status || 500
if (statusCode === 404) {
throw createError({
statusCode: 404,
message: 'The license was not found.',
data: {
report: false,
},
fatal: true,
})
}
throw createError({
statusCode: 404,
message: 'The license was not found.',
statusCode: statusCode,
message: 'Something went wrong while fetching the licenses.',
fatal: true,
})
}
}
@@ -181,8 +181,20 @@ const { data, error } = await useAsyncData('licensesPage', async () => {
instanceId: instanceData.instance_id,
}
} catch (e) {
const statusCode = e.response?.status || 500
if (statusCode === 404) {
throw createError({
statusCode: 404,
message: 'Licenses not found.',
data: {
report: false,
},
fatal: true,
})
}
throw createError({
statusCode: 400,
statusCode: statusCode,
message: 'Something went wrong while fetching the licenses.',
fatal: true,
})
Whitespace-only changes.
@@ -0,0 +1,43 @@
import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { normalizeError } from '@baserow/modules/database/utils/errors'
export default defineNuxtRouteMiddleware(async (to) => {
const { $store } = useNuxtApp()
const automationId = parseInt(to.params.automationId)
const workflowId = parseInt(to.params.workflowId)
try {
const automation = await $store.dispatch(
'application/selectById',
automationId
)
await $store.dispatch('workspace/selectById', automation.workspace.id)
await $store.dispatch('automationWorkflow/selectById', {
automation,
workflowId,
})
} catch (e) {
const isStoreLookupError = e instanceof StoreItemLookupError
if (e.response === undefined && !isStoreLookupError) {
throw e
}
const errorStatus =
isStoreLookupError || !e.response?.status ? 404 : e.response.status
throw createError({
statusCode: errorStatus,
message:
errorStatus === 404
? 'Automation workflow not found.'
: normalizeError(e).message,
data: {
report: errorStatus !== 404,
},
fatal: true,
})
}
})
@@ -3,6 +3,7 @@ import {
addPlugin,
createResolver,
extendPages,
addRouteMiddleware,
} from 'nuxt/kit'
import { routes } from './routes'
import { locales } from '../../config/locales.js'
@@ -24,6 +25,11 @@ export default defineNuxtModule({
src: resolve('./plugins/realtime.js'),
})
addRouteMiddleware({
name: 'selectWorkspaceAutomationWorkflow',
path: resolve('./middleware/selectWorkspaceAutomationWorkflow.js'),
})
extendPages((pages) => {
pages.push(...routes)
})
@@ -16,6 +16,7 @@ import { onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router'
import AutomationWorkflowContent from '@baserow/modules/automation/components/AutomationWorkflowContent'
import { AutomationApplicationType } from '@baserow/modules/automation/applicationTypes'
import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { normalizeError } from '@baserow/modules/database/utils/errors'
definePageMeta({
layout: 'app',
@@ -23,6 +24,7 @@ definePageMeta({
'settings',
'authenticated',
'workspacesAndApplications',
'selectWorkspaceAutomationWorkflow',
'pendingJobs',
],
})
@@ -38,29 +40,6 @@ const workflowLoading = ref(false)
const route = useRoute()
const { $store, $registry } = useNuxtApp()
// Parse route params once at setup time
const automationId = computed(() => {
const param = route.params.automationId
if (typeof param === 'string') {
return parseInt(param, 10)
}
if (typeof param === 'number') {
return param
}
return null
})
const workflowId = computed(() => {
const param = route.params.workflowId
if (typeof param === 'string') {
return parseInt(param, 10)
}
if (typeof param === 'number') {
return param
}
return null
})
// Load page data
const automationApplicationType = $registry.get(
'application',
@@ -68,26 +47,16 @@ const automationApplicationType = $registry.get(
)
const { data: pageData, error } = await useAsyncData(
() => `automation-workflow-${automationId.value}-${workflowId.value}`,
() =>
`automation-workflow-${route.params.automationId}-${route.params.workflowId}`,
async () => {
try {
const automation = await $store.dispatch(
'application/selectById',
automationId.value
)
const workspace = await $store.dispatch(
'workspace/selectById',
automation.workspace.id
)
const automation = $store.getters['application/getSelected']
const workspace = $store.getters['workspace/getSelected']
const workflow = $store.getters['automationWorkflow/getSelected']
await automationApplicationType.loadExtraData(automation)
const workflow = await $store.dispatch('automationWorkflow/selectById', {
automation,
workflowId: workflowId.value,
})
await $store.dispatch('automationWorkflowNode/fetch', {
workflow,
})
@@ -100,9 +69,22 @@ const { data: pageData, error } = await useAsyncData(
workflow,
}
} catch (e) {
if (e.response === undefined && !(e instanceof StoreItemLookupError)) {
throw e
}
const statusCode = e.response?.status || 500
throw createError({
statusCode: 404,
message: 'Automation workflow not found.',
statusCode,
message:
statusCode === 404
? 'Automation workflow not found.'
: normalizeError(e).message,
data: {
report: statusCode >= 500,
},
fatal: true,
})
}
}
@@ -1,15 +1,22 @@
<template>
<div v-if="!redirecting" class="placeholder">
<div class="placeholder__logo">
<nuxt-link
:to="{
name: routeName,
params: { pathMatch: '' },
}"
custom
<a
:href="
$router.resolve({
name: routeName,
params: { pathMatch: '' },
}).fullPath
"
@click.prevent="
clearAndNavigate({
name: routeName,
params: { pathMatch: '' },
})
"
>
<Logo class="placeholder__logo-image" />
</nuxt-link>
</a>
</div>
<h1 class="placeholder__title">{{ message }}</h1>
<p v-if="error.statusCode === 404" class="placeholder__content">
@@ -57,7 +64,10 @@ export default {
},
},
methods: {
onHome() {
clearAndNavigate(to) {
window.location.replace(this.$router.resolve(to).fullPath)
},
async onHome() {
if (
['application-builder-page', 'application-builder-preview'].includes(
this.routeName
@@ -68,7 +78,7 @@ export default {
this.$router.go(0)
} else {
// Navigate to the home route
this.$router.push({
this.clearAndNavigate({
name: this.routeName,
params: { pathMatch: '' },
query: null, // Remove query parameters
@@ -1,3 +0,0 @@
/**
* Nothing here yet
*/
@@ -1,4 +1,5 @@
import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { normalizeError } from '@baserow/modules/database/utils/errors'
export default defineNuxtRouteMiddleware(async (to, from) => {
const { $store, $i18n } = useNuxtApp()
@@ -18,13 +19,24 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
pageId,
})
} catch (e) {
if (e.response === undefined && !(e instanceof StoreItemLookupError)) {
const isStoreLookupError = e instanceof StoreItemLookupError
if (e.response === undefined && !isStoreLookupError) {
throw e
}
const errorStatus =
isStoreLookupError || !e.response?.status ? 404 : e.response.status
throw createError({
statusCode: 404,
message: $i18n.t('pageEditor.pageNotFound'),
statusCode: errorStatus,
message:
errorStatus === 404
? $i18n.t('pageEditor.pageNotFound')
: normalizeError(e).message,
data: {
report: errorStatus !== 404,
},
fatal: true,
})
}
})
@@ -12,6 +12,7 @@ import { useHead, useAsyncData } from '#imports'
import { computed } from 'vue'
import { onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router'
import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { normalizeError } from '@baserow/modules/database/utils/errors'
import { DataProviderType } from '@baserow/modules/core/dataProviderTypes'
import { BuilderApplicationType } from '@baserow/modules/builder/applicationTypes'
import _ from 'lodash'
@@ -46,8 +47,8 @@ const {
() => `page-editor-${route.params.builderId}-${route.params.pageId}`,
async () => {
// The objects are selected by the middleware
const loadedBuilder = $store.getters['application/getSelected']
const loadedWorkspace = $store.getters['workspace/getSelected']
const loadedBuilder = $store.getters['application/getSelected']
const page = $store.getters['page/getSelected']
try {
@@ -64,6 +65,10 @@ const {
throw createError({
statusCode: 404,
message: $i18n.t('pageEditor.pageNotFound'),
data: {
report: false,
},
fatal: true,
})
}
@@ -95,9 +100,18 @@ const {
throw e
}
const statusCode = e.response?.status || 500
throw createError({
statusCode: 404,
message: $i18n.t('pageEditor.pageNotFound'),
statusCode,
message:
statusCode === 404
? $i18n.t('pageEditor.pageNotFound')
: normalizeError(e).message,
data: {
report: statusCode >= 500,
},
fatal: true,
})
}
}
@@ -98,6 +98,10 @@ const {
throw createError({
statusCode: 404,
message: $i18n.t('publicPage.siteNotFound'),
data: {
report: false,
},
fatal: true,
})
}
@@ -174,6 +178,10 @@ const {
throw createError({
statusCode: authError.code,
message: authError.message,
data: {
report: false,
},
fatal: true,
})
}
}
@@ -191,6 +199,10 @@ const {
throw createError({
statusCode: 404,
message: $i18n.t('publicPage.pageNotFound'),
data: {
report: false,
},
fatal: true,
})
}
@@ -200,6 +212,10 @@ const {
throw createError({
statusCode: 404,
message: $i18n.t('publicPage.pageNotFound'),
data: {
report: false,
},
fatal: true,
})
}
@@ -239,6 +255,10 @@ const {
throw createError({
statusCode: 404,
statusMessage: $i18n.t('publicPage.pageNotFound'),
data: {
report: false,
},
fatal: true,
})
} else {
throw error
@@ -1,9 +1,12 @@
<template>
<div v-if="!redirecting" class="placeholder">
<div class="placeholder__logo">
<nuxt-link :to="{ name: 'index' }">
<a
:href="$router.resolve({ name: 'index' }).fullPath"
@click.prevent="clearAndNavigate({ name: 'index' })"
>
<Logo class="placeholder__logo-image" />
</nuxt-link>
</a>
</div>
<h1 class="placeholder__title">{{ message }}</h1>
<p v-if="error.statusCode === 404" class="placeholder__content">
@@ -17,30 +20,32 @@
icon="iconoir-redo"
@click="refresh"
>
{{ $t('errorLayout.refresh') }}</Button
>
{{ $t('errorLayout.refresh') }}
</Button>
<Button
v-else-if="isAuthenticated && currentRouteName !== 'dashboard'"
tag="nuxt-link"
:to="{ name: 'dashboard' }"
tag="a"
:href="$router.resolve({ name: 'dashboard' }).fullPath"
type="primary"
size="large"
icon="iconoir-nav-arrow-left"
@click.prevent="clearAndNavigate({ name: 'dashboard' })"
>
{{ $t('errorLayout.backDashboard') }}
</Button>
<Button
v-else
tag="nuxt-link"
:to="{ name: 'login' }"
tag="a"
:href="$router.resolve({ name: 'login' }).fullPath"
type="primary"
size="large"
icon="iconoir-nav-arrow-left"
@click.prevent="clearAndNavigate({ name: 'login' })"
>
{{ $t('errorLayout.backLogin') }}</Button
>
{{ $t('errorLayout.backLogin') }}
</Button>
</div>
</div>
</template>
@@ -99,6 +104,9 @@ export default {
}
},
methods: {
clearAndNavigate(to) {
window.location.replace(this.$router.resolve(to).fullPath)
},
refresh() {
location.reload()
},
-19
View File
@@ -1,19 +0,0 @@
import settings from '@baserow/modules/core/middleware/settings'
import authentication from '@baserow/modules/core/middleware/authentication'
import authenticated from '@baserow/modules/core/middleware/authenticated'
import staff from '@baserow/modules/core/middleware/staff'
import workspacesAndApplications from '@baserow/modules/core/middleware/workspacesAndApplications'
import pendingJobs from '@baserow/modules/core/middleware/pendingJobs'
import urlCheck from '@baserow/modules/core/middleware/urlCheck'
import impersonate from '@baserow/modules/core/middleware/impersonate'
import Middleware from './middleware'
Middleware.settings = settings
Middleware.authentication = authentication
Middleware.authenticated = authenticated
Middleware.staff = staff
Middleware.workspacesAndApplications = workspacesAndApplications
Middleware.pendingJobs = pendingJobs
Middleware.urlCheck = urlCheck
Middleware.impersonate = impersonate
+10 -1
View File
@@ -12,6 +12,15 @@ export default defineNuxtRouteMiddleware(() => {
// If the user is not staff we want to show a forbidden error.
if (!$store.getters['auth/isStaff']) {
throw createError({ statusCode: 403, message: 'Forbidden.' })
return abortNavigation(
createError({
statusCode: 403,
message: 'Forbidden.',
data: {
report: false,
},
fatal: true,
})
)
}
})
-1
View File
@@ -112,7 +112,6 @@ export default defineNuxtModule({
)
addPlugin(resolve('plugins/store.js'))
addPlugin(resolve('plugins/errorHandler.js'))
addPlugin(resolve('plugins/filters.js'))
addPlugin(resolve('plugins/vuexState.js'))
addPlugin(resolve('plugin.js'))
@@ -25,6 +25,10 @@ const { data: notification, error: loadError } = await useAsyncData(
throw createError({
statusCode: 404,
message: 'Notification not found.',
data: {
report: false,
},
fatal: true,
})
}
}
@@ -44,6 +48,10 @@ if (!redirectParams) {
throw createError({
statusCode: 404,
message: 'Notification has no route.',
data: {
report: false,
},
fatal: true,
})
}
+8 -1
View File
@@ -49,7 +49,14 @@ const { data: workspace, error } = await useAsyncData('workspace', async () => {
parseInt(route.params.workspaceId, 10)
)
} catch (e) {
throw createError({ statusCode: 404, message: 'Workspace not found.' })
throw createError({
statusCode: 404,
message: 'Workspace not found.',
data: {
report: false,
},
fatal: true,
})
}
})
+71 -1
View File
@@ -592,7 +592,7 @@
</template>
</Alert>
<Alert type="danger" close-button>
<Alert type="error" close-button>
<template #title>Alert title</template>
<template #actions>
<button
@@ -1953,6 +1953,73 @@
Call to action with an icon
</CallToAction>
</div>
<div class="margin-bottom-3">
<div class="margin-bottom-3">
<nuxt-link
:to="{
name: 'builder-page',
params: {
builderId: 99,
pageId: 99,
},
}"
>
<Button type="primary" size="small">
To missing builder page
</Button>
</nuxt-link>
</div>
<div class="margin-bottom-3">
<nuxt-link
:to="{
name: 'database-table',
params: {
databaseId: 9999,
tableId: 99,
viewId: 99,
},
}"
>
<Button type="primary" size="small">
To missing database table
</Button>
</nuxt-link>
</div>
<div class="margin-bottom-3">
<nuxt-link
:to="{
name: 'dashboard-application',
params: {
dashboardId: 9999,
},
}"
>
<Button type="primary" size="small">
To missing dashboard
</Button>
</nuxt-link>
</div>
<div class="margin-bottom-3">
<nuxt-link
:to="{
name: 'automation-workflow',
params: {
automationId: 999,
workflowId: 999,
},
}"
>
<Button type="primary" size="small">
To missing automation workflow
</Button>
</nuxt-link>
</div>
<div>
<Button type="primary" size="small" @click="triggerError">
Trigger fake error
</Button>
</div>
</div>
<br /><br /><br />
<br /><br /><br />
<br /><br /><br />
@@ -2020,6 +2087,9 @@ export default {
alert(message) {
alert(message)
},
triggerError() {
throw new Error('Fake error')
},
},
}
</script>
@@ -68,11 +68,19 @@ const { data: result, error } = await useAsyncData('verify-email', async () => {
throw createError({
statusCode: 401,
message: t('error.disabledAccountMessage'),
data: {
report: false,
},
fatal: true,
})
} else if (response.data?.error === 'ERROR_AUTH_PROVIDER_DISABLED') {
throw createError({
statusCode: 401,
message: t('verifyEmailAddress.disabledPasswordProvider'),
data: {
report: false,
},
fatal: true,
})
}
}
@@ -80,6 +88,10 @@ const { data: result, error } = await useAsyncData('verify-email', async () => {
throw createError({
statusCode: 404,
message: t('verifyEmailAddress.invalidToken'),
data: {
report: false,
},
fatal: true,
})
}
})
@@ -321,6 +321,10 @@ const {
throw createError({
statusCode: 404,
message: 'Workspace not found.',
data: {
report: false,
},
fatal: true,
})
}
@@ -331,6 +335,10 @@ const {
throw createError({
statusCode: 400,
message: 'Error loading dashboard.',
data: {
report: false,
},
fatal: true,
})
}
}
@@ -1,14 +0,0 @@
import { showError } from '#imports'
export default defineNuxtPlugin((nuxtApp) => {
const defaultHandler = nuxtApp.vueApp.config.errorHandler
nuxtApp.vueApp.config.errorHandler = (error, instance, info) => {
if (error.fatal === false) {
showError(error)
return false
} else {
return defaultHandler(error, instance, info)
}
}
})
@@ -1,6 +0,0 @@
// import dashboardLoading from '@baserow/modules/dashboard/middleware/dashboardLoading'
// /* eslint-disable-next-line */
// import Middleware from './middleware'
// Middleware.dashboardLoading = dashboardLoading
@@ -1,4 +1,5 @@
import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { normalizeError } from '@baserow/modules/database/utils/errors'
/**
* Middleware that changes the dashboard loading state to true before the route
@@ -28,10 +29,18 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
if (e.response === undefined && !(e instanceof StoreItemLookupError)) {
throw e
}
const errorStatus = e.response?.status || 404
throw createError({
statusCode: 404,
message: 'Dashboard not found.',
statusCode: errorStatus,
message:
errorStatus === 404
? 'Dashboard not found.'
: normalizeError(e).message,
data: {
report: errorStatus !== 404,
},
fatal: true,
})
}
}
@@ -1,5 +1,5 @@
<template>
<div class="dashboard-app">
<div v-if="dashboard" class="dashboard-app">
<DashboardHeader :dashboard="dashboard" />
<DashboardContent :dashboard="dashboard" />
</div>
@@ -8,8 +8,10 @@
<script setup>
import { computed, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { useRoute } from 'vue-router'
import { useNuxtApp, useAsyncData, createError, useHead } from '#app'
import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { normalizeError } from '@baserow/modules/database/utils/errors'
import DashboardHeader from '@baserow/modules/dashboard/components/DashboardHeader'
import DashboardContent from '@baserow/modules/dashboard/components/DashboardContent'
@@ -35,11 +37,43 @@ const {
} = await useAsyncData(
`dashboard-data-${route.params.dashboardId}`,
async () => {
const dashboard = store.getters['application/getSelected']
const workspace = store.getters['workspace/getSelected']
return {
workspace,
dashboard,
try {
const dashboard = store.getters['application/getSelected']
const workspace = store.getters['workspace/getSelected']
const forEditing = $hasPermission(
'application.update',
dashboard,
workspace.id
)
await store.dispatch('dashboardApplication/fetchInitial', {
dashboardId: dashboard.id,
forEditing,
})
return {
workspace,
dashboard,
}
} catch (e) {
if (e.response === undefined && !(e instanceof StoreItemLookupError)) {
throw e
}
const statusCode = e.response?.status || 500
throw createError({
statusCode,
message:
statusCode === 404
? 'Dashboard not found.'
: normalizeError(e).message,
data: {
report: statusCode >= 500,
},
fatal: true,
})
}
}
)
@@ -49,7 +83,6 @@ if (fetchError.value) {
}
const dashboard = computed(() => data.value?.dashboard)
const workspace = computed(() => data.value?.workspace)
useHead(() => ({
title: dashboard.value?.name || '',
@@ -57,17 +90,6 @@ useHead(() => ({
// Mounted logic
onMounted(() => {
const forEditing = $hasPermission(
'application.update',
dashboard.value,
workspace.value.id
)
store.dispatch('dashboardApplication/fetchInitial', {
dashboardId: dashboard.value.id,
forEditing,
})
if (dashboard.value) {
$realtime.subscribe('dashboard', { dashboard_id: dashboard.value.id })
}
-5
View File
@@ -5,10 +5,5 @@ export const routes = [
name: 'dashboard-application',
path: '/dashboard/:dashboardId',
file: path.resolve(__dirname, 'pages/dashboard.vue'),
// props(route) {
// const p = { ...route.params }
// p.dashboardId = parseInt(p.dashboardId)
// return p
// },
},
]
@@ -1,5 +0,0 @@
import tableLoading from '@baserow/modules/database/middleware/tableLoading'
import Middleware from './middleware'
Middleware.tableLoading = tableLoading
@@ -20,11 +20,22 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
table = result.table
await $store.dispatch('workspace/selectById', database.workspace.id)
} catch (e) {
if (e.response === undefined && !(e instanceof StoreItemLookupError))
const isStoreLookupError = e instanceof StoreItemLookupError
if (e.response === undefined && !isStoreLookupError) {
throw e
}
const errorStatus =
isStoreLookupError || !e.response?.status ? 404 : e.response.status
throw createError({
statusCode: e.response?.status || 404,
message: normalizeError(e).message,
statusCode: errorStatus,
message:
errorStatus === 404 ? 'Table not found.' : normalizeError(e).message,
data: {
report: errorStatus !== 404,
},
fatal: true,
})
}
-33
View File
@@ -1,36 +1,3 @@
/*import path from 'path'
import { routes } from './routes'
import en from './locales/en.json'
import fr from './locales/fr.json'
import nl from './locales/nl.json'
import de from './locales/de.json'
import it from './locales/it.json'
import es from './locales/es.json'
import pl from './locales/pl.json'
import ko from './locales/ko.json'
export default function DatabaseModule(options) {
this.addPlugin({ src: path.resolve(__dirname, 'middleware.js') })
// Add the plugin to register the database application.
this.appendPlugin({
src: path.resolve(__dirname, 'plugin.js'),
})
// Add all the related routes.
this.extendRoutes((configRoutes) => {
configRoutes.push(...routes)
})
let alreadyExtended = false
this.nuxt.hook('i18n:extend-messages', function (additionalMessages) {
if (alreadyExtended) return
additionalMessages.push({ en, fr, nl, de, es, it, pl, ko })
alreadyExtended = true
})
}*/
import {
defineNuxtModule,
addPlugin,
+16 -2
View File
@@ -110,7 +110,14 @@ const { data, error } = await useAsyncData(
}),
}
} else {
throw createError({ statusCode: 404, message: 'Form not found.' })
throw createError({
statusCode: 404,
message: 'Form not found.',
data: {
report: false,
},
fatal: true,
})
}
}
@@ -169,7 +176,14 @@ const { data, error } = await useAsyncData(
Object.assign(values, rowData)
} catch (e) {
if (e.response.status === 404) {
throw createError({ statusCode: 404, message: 'Invalid edit token.' })
throw createError({
statusCode: 404,
message: 'Invalid edit token.',
data: {
report: false,
},
fatal: true,
})
}
throw e
}
@@ -130,7 +130,14 @@ const { data, error } = await useAsyncData(
},
}
} else if (statusCode === 404) {
throw createError({ statusCode: 404, message: 'View not found.' })
throw createError({
statusCode: 404,
message: 'View not found.',
data: {
report: false,
},
fatal: true,
})
} else {
throw createError({
statusCode: 500,
+5 -2
View File
@@ -31,8 +31,11 @@ if (dsn && dsn !== '') {
...(isDev ? { transport: makeFakeTransport } : {}),
beforeSend(event, hint) {
const err = hint?.originalException
if (err?.fatal === false) return null
if (err?.fatal === false) {
return null
} else if (err?.fatal === true && err?.data?.report === false) {
return null
}
// Filter out axios errors without a response like
// network error, timeout, aborted, cancelled requests
if (err?.name === 'AxiosError' && !err?.response) {
+5 -1
View File
@@ -19,7 +19,11 @@ if (dsn && dsn !== '') {
...(isDev ? { transport: makeFakeTransport } : {}),
beforeSend(event, hint) {
const err = hint?.originalException
if (err?.fatal === false) return null
if (err?.fatal === false) {
return null
} else if (err?.fatal === true && err?.data?.report === false) {
return null
}
// Filter known API errors that are handled by the application (e.g. forceLogoff).
const status = err?.response?.status || err?.statusCode