在IHP中自定义404页面的步骤如下:
ErrorController
的控制器,该控制器负责处理错误请求。ErrorController
中定义一个名为notFoundAction
的动作方法,用于处理404错误。notFoundAction
方法中,可以编写自定义的404页面逻辑,例如加载一个特定的模板或返回一个自定义的错误信息。routes.hs
文件中,将404错误路由到ErrorController
的notFoundAction
方法。示例代码如下:
-- ErrorController.hs
module Web.Controller.Error where
import IHP.ControllerPrelude
instance Controller ErrorController where
beforeAction = setLayout defaultLayout
action NotFoundAction = do
render NotFoundView
data NotFoundView = NotFoundView
instance View NotFoundView where
html NotFoundView = [hsx|
<h1>404 Not Found</h1>
<p>Sorry, the page you requested does not exist.</p>
|]
-- routes.hs
instance FrontController WebApplication where
...
controllers =
...
, parseRoute @ErrorController
...
-- Main.hs
main = do
-- 进行其他设置...
runRIO App {..} $ do
let ?modelContext = db
startWebServer port
-- Application.hs
instance CanRoute ErrorController where
parseRoute' = do
string "/error"
action <- parseRoute'
pure (ErrorController, action)
dispatch' ErrorController = do
let controller = ErrorController
action <- requireAction
case action of
NotFoundAction -> autoRefresh do
ensureResponseContainsStatus status404
controller |> action
以上代码片段展示了如何在IHP中自定义404页面。当访问一个不存在的页面时,IHP将调用ErrorController
的notFoundAction
方法来渲染自定义的404页面。你可以在NotFoundView
中编写HTML模板,显示适当的错误信息。请注意,在路由配置中将404错误路由到ErrorController
的NotFoundAction
方法,以确保正确的处理流程。
腾讯云相关产品和产品介绍链接地址,请参考腾讯云官方文档:腾讯云产品文档。
领取专属 10元无门槛券
手把手带您无忧上云