fix(logs): don't spam the logs with 404 and add better logging for server errors

This commit is contained in:
William Oldham
2026-08-29 19:14:48 +01:00
parent 20ca7d55ff
commit b1866617c6
2 changed files with 43 additions and 3 deletions

View File

@@ -0,0 +1,38 @@
import type { H3Error } from 'h3';
/**
* Logs server-side errors in a compact, readable format.
*
* Nitro fires the `error` hook for every request error, whatever the source
* (API routes, server routes/middleware, SSR rendering). It also fires for
* expected HTTP errors like 404s, so anything below a 500 is ignored here.
*/
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('error', (err, { event }) => {
const error = err as Partial<H3Error>;
const statusCode = error.statusCode ?? 500;
// Skip expected client errors (404, 401, 422, redirects, ...).
if (statusCode < 500) {
return;
}
const where = event ? `${event.method} ${event.path}` : 'non-request';
const tag = error.unhandled ? '[unhandled]' : '';
console.error(`[server error] ${tag} ${where} -> ${statusCode} ${err.message}`);
if (error.data !== undefined) {
console.error(' data:', error.data);
}
if (err.cause) {
console.error(' cause:', err.cause);
}
if (err.stack) {
// Drop the first line (already printed above as the message).
console.error(err.stack.split('\n').slice(1).join('\n'));
}
});
});

View File

@@ -3,9 +3,11 @@ import { watchImmediate } from '@vueuse/core';
import DefaultLayout from './layouts/default.vue';
const { error } = defineProps<{ error: any }>();
watchImmediate([error], () => {
console.error(error);
});
if (import.meta.client) {
watchImmediate([() => error], () => {
console.error(error);
});
}
</script>
<template>