我正在将我的小网站从express + handlebars转换为express + sapper项目。
我想捕获服务器端错误(例如,进入/ api / error时发生的自愿错误),并使用sapper _error.svelte 模板来呈现它们。
我尝试仅在没有我的自定义处理程序的情况下抛出错误,但是它返回的丑陋的文本页面仅包含错误堆栈,似乎没有被sapper的错误处理程序捕获
所以我添加了自己的错误处理程序,并且可以呈现HTML(裸露,尚无CSS),但是有没有办法使用sapper _error.svelte模板?
// ----------------------- src/server.js
import sirv from 'sirv'
import express from 'express'
import compression from 'compression'
import * as sapper from '@sapper/server'
import fatal500 from './middlewares/fatal500'
const { PORT, NODE_ENV } = process.env
const dev = NODE_ENV === 'development'
const app = express()
app.use(compression({ threshold: 0 }))
app.use(sirv('static', { dev }))
// the voluntary error thrower --------------------------------
app.get('/api/error', (req, res, next) => {
const error = new Error('this is a voluntary error')
error.code = 'VOLUNTARY'
next(error)
})
app.use(sapper.middleware())
app.use(fatal500) // the custom error handler -----------
app.listen(PORT, err => {
if (err) console.log('error', err)
})
// ---------------------src/middlewares/fatal500.js
export default function fatal500 (err, req, res, next) {
if (err.code !== 'VOLUNTARY') console.error(err.stack)
try {
res.status(500)
.type('html')
.send(
'<h1>Oooops ... 500 server error</h1>' +
'<p>It seems the server has encountered an error,<br/>' +
' try to <a href=\'/\'> return to the website</a><br/>' +
' or to <a href="mailto:mail@mail.mail">send me the stack</a>' +
'</p>' +
'<h2>Error Stack :</h2>' +
'<pre class="code"><code>' +
err.stack +
'</code></pre>'
)
} catch (e) {
res.status(500)
.type('text')
.send(
'\n\n' +
'**************************************\n' +
'Ooops ... 500\n' +
'the server encountered an unhandled error,\n\n' +
'if it is not voluntary (going to /api/error)\n' +
'please EMAIL ME THE FOLLOWING STACK at\n' +
'mail@mail.mail\n' +
'**************************************\n\n' +
'ORIGINAL ERROR STACK ------------------\n\n' +
err.stack + '\n\n' +
'ERROR HANDLING STACK ------------------\n\n' +
e.stack
)
}
}
答案 0 :(得分:1)
众所周知,Javascript 很难捕获所有类型的错误。Sapper 也没有对这些错误进行任何显式处理,但是有一个简洁的第三方组件可以实现这一点。
我个人使用的第一种方法是这个库:https://www.npmjs.com/package/@crownframework/svelte-error-boundary
本质上会在组件边界捕获错误(在合理范围内)。它提供了一种附加函数的方法,以便您可以针对该错误执行您喜欢的操作。
我目前正在将其构建到 Svelte 本身中。您可以反馈 RFC https://github.com/sveltejs/rfcs/blob/rfc/error-boundary/text/0000-error-boundary.md
我使用边界的方式是将处理程序附加到 sentry
- https://sentry.io,它会为您分解和诊断问题,以便您可以修复它们。看看!