自定义404

webman在404时会自动返回public/404.html里面的内容,所以开发者可以直接更改public/404.html文件。

如果你想动态控制404的内容时,例如在ajax请求时返回json数据 {"code:"404", "msg":"404 not found"},页面请求时返回app/view/404.html模版,请参考如下示例

创建文件app/view/404.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>404 not found</title>
  6. </head>
  7. <body>
  8. <?=htmlspecialchars($error)?>
  9. </body>
  10. </html>

config/route.php中加入如下代码:

  1. use support\Request;
  2. use Webman\Route;
  3. Route::fallback(function(Request $request){
  4. // ajax请求时返回json
  5. if ($request->expectsJson()) {
  6. return json(['code' => 404, 'msg' => '404 not found']);
  7. }
  8. // 页面请求返回404.html模版
  9. return view('404', ['error' => 'some error']);
  10. });

自定义500

新建app/view/500.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>500 Internal Server Error</title>
  6. </head>
  7. <body>
  8. 自定义错误模版:
  9. <?=htmlspecialchars($exception)?>
  10. </body>
  11. </html>

新建app/exception/Handler.php(如目录不存在请自行创建)

  1. <?php
  2. namespace app\exception;
  3. use Throwable;
  4. use Webman\Http\Request;
  5. use Webman\Http\Response;
  6. class Handler extends \support\exception\Handler
  7. {
  8. /**
  9. * 渲染返回
  10. * @param Request $request
  11. * @param Throwable $exception
  12. * @return Response
  13. */
  14. public function render(Request $request, Throwable $exception) : Response
  15. {
  16. $code = $exception->getCode();
  17. // ajax请求返回json数据
  18. if ($request->expectsJson()) {
  19. return json(['code' => $code ? $code : 500, 'msg' => $exception->getMessage()]);
  20. }
  21. // 页面请求返回500.html模版
  22. return view('500', ['exception' => $exception]);
  23. }
  24. }

配置config/exception.php

  1. return [
  2. '' => \app\exception\Handler::class,
  3. ];