流明中的自定义404页面 [英] Custom 404 page in Lumen

查看:68
本文介绍了流明中的自定义404页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Lumen的新手,并希望使用此框架创建一个应用程序.现在,我遇到的问题是,如果某些用户输入了错误的网址=> http://www.example.com/abuot (错误)=> http://www.example.com/about (正确),我想展示一个自定义错误页面,这将是在中间件级别进行的理想选择.

I'm new to Lumen and want to create an app with this framework. Now I have the problem that if some user enters a wrong url => http://www.example.com/abuot (wrong) => http://www.example.com/about (right), I want to present a custom error page and it would be ideal happen within the middleware level.

此外,我能够检查当前url是否有效,但是我不确定如何在中间件中创建"视图,response()-> view()将不起作用.

Furthermore, I am able to check if the current url is valid or not, but I am not sure how can I "make" the view within the middleware, the response()->view() won't work.

如果有人可以帮忙,那真是太棒了.

Would be awesome if somebody can help.

推荐答案

看到错误是在 App \ Exceptions \ Handler 中处理的,这是处理它们的最佳位置.

Seeing as errors are handled in App\Exceptions\Handler, this is the best place to deal with them.

如果仅在自定义404错误页面之后,那么您可以很容易地做到这一点:

If you are only after a custom 404 error page, then you could do this quite easily:

将此行添加到 Handler 文件的顶部:

Add this line up the top of the Handler file:

使用Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException;

更改 render 函数的外观如下:

public function render($request, Exception $e)
{
    if($e instanceof NotFoundHttpException){
        return response(view("errors.404"), 404);
    }
    return parent::render($request, $e);
}

这假设您的自定义404页面存储在视图内的错误文件夹中,并将返回自定义错误页面以及404状态代码.

This assumes your custom 404 page is stored in an errors folder within your views, and will return the custom error page along with a 404 status code.

这篇关于流明中的自定义404页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆