扫码关注官方订阅号
比如正常的一个请求,返回方式如下:
return response($result, $code); // 返回json
异常的请求,比如该路由没有被定义,该请求的方法没有被定义。如何也返回一个json对象呢,写在404.blade.php里肯定不合适,因为写进去的话会返回一个string
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
在Middleware或者App\Exceptions\Handler里捕获Symfony\Component\HttpKernel\Exception\NotFoundHttpException
Middleware
App\Exceptions\Handler
Symfony\Component\HttpKernel\Exception\NotFoundHttpException
如果是Middleware
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; public function handle($request, Closure $next) { try { return $next($request); } catch (NotFoundHttpException $e) { return response()->json(['msg'=>'NotFound']); } }
2017.04.04 更新
已知laravel5的默认Exceptions\Handler会优先匹配404异常,所以建议在Handler进行处理。
laravel5
Exceptions\Handler
Handler
修改app/Exceptions/Handler.php的render方法如下
app/Exceptions/Handler.php
render
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { if (is_a($exception, \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class) && $request->expectsJson()) { return response()->json(['msg'=>'NotFound']); } else { return parent::render($request, $exception); } }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
在
Middleware或者App\Exceptions\Handler里捕获Symfony\Component\HttpKernel\Exception\NotFoundHttpException如果是Middleware
2017.04.04 更新
已知
laravel5的默认Exceptions\Handler会优先匹配404异常,所以建议在Handler进行处理。修改
app/Exceptions/Handler.php的render方法如下