Lumen custom page-notfound response

Lumen custom page-notfound response

Notice: This article is only a available in Chinese version available. :(


在 App\Exceptions\Handler 中引入:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

然后在render()中更改响应的方式。
如果要渲染成页面,可以先在view文件夹中添加error.blade.php文件,然后在render()return前加入判断404的语句:

if ($e instanceof NotFoundHttpException){
    return response(view("error"),404);
}

如果要渲染成Json格式输出,可以直接使用json():

if ($e instanceof NotFoundHttpException){
    return response()->json(
        [
            'code' => 'E201',
            'message' => 'Request failure : requested route not found'
        ]
    );
}