laravel HTTP路由可带正则表达式验证,不符合规则的会报错,这样不友好,该如何设置报错信息?
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
Route::get('user/{id}', function($id)
{
//
})
->where('id', '[0-9]+');
线上debug是必须关闭的,而且可以自定义404页面
NotFoundHttpException 异常,在 app/Exceptions/Handler 里捕获一下
<?php namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
//'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
*
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
*
* @return \Illuminate\Http\Response
*/
public function render($request,Exception $e)
{
if($e instanceof NotFoundHttpException)
{
return \Response::view('sys::missing',[],404); //你需要的在这里,404
}
//其他一些异常 照着写就行了
//...
}
}
php
/** * Render the given HttpException. * * @param \Symfony\Component\HttpKernel\Exception\HttpException $e * @return \Symfony\Component\HttpFoundation\Response */ protected function renderHttpException(HttpException $e) { if (view()->exists('errors.'.$e->getStatusCode())) { return response()->view('errors.'.$e->getStatusCode(), [], $e->getStatusCode()); } else { return (new SymfonyDisplayer(config('app.debug')))->createResponse($e); } } 比如你想自定义 404 错误页面的话,只要创建一个 resources/views/errors/404.blade.php 的视图文件 404内容自定义了
直接放个404页面到errors文件夹即可。