如何在Laravel 5中为HTTP错误响应返回自定义视图? [英] How to return custom view for http error response in Laravel 5?

查看:122
本文介绍了如何在Laravel 5中为HTTP错误响应返回自定义视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在应用程序中返回http错误响应时,如何为每个http错误响应定义自定义View文件,然后要求laravel自动将该视图文件发送给用户?

How Can I define custom View files for each of http error responses and then ask laravel to send that view file automatically to user when I'm returning an http error response in my application?

推荐答案

基本上,您可以为每个HTTP错误代码定义一个页面并将其放入resources/views/errors/

Basically you can define a page for every HTTP error code and put it in resources/views/errors/

因此,如果要为404 HTTP响应创建视图,则应创建视图:

So, if you want to create a view for a 404 HTTP response you should create the view:

resources/views/errors/404.blade.php

Laravel会自动将您的用户重定向到特定视图

and Laravel will redirect automatically your users to the specific view

此外,您可以自定义App\Exceptions\Handler类,该类负责处理来自异常的错误:每次Exception出现时,都会调用render方法,因此您可以拦截由HTTP错误生成的HttpException,重定向到您想要的任何地方:

Additionally, you can customize the App\Exceptions\Handler class that is responsable for rendering errors from exceptions: the render method is called everytime an Exception rises, so you can intercept the HttpException generated by the HTTP error and redirect wherever you want:

public function render($request, Exception $e)
{
    //if $e is an HttpException
    if ($e instanceof HttpException ) {

        //get the status code 
        $status = $e->getStatusCode() ;

        //if status code is 501 redirect to custom view
        if( $status == 501 )
            return response()->view('my.custom.view', [], 501);
    }

    return parent::render($request, $e);
}

这篇关于如何在Laravel 5中为HTTP错误响应返回自定义视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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