Home > Backend Development > PHP Tutorial > Laravel5.x如何让404返回一个json?

Laravel5.x如何让404返回一个json?

WBOY
Release: 2016-06-06 20:31:56
Original
1075 people have browsed it

比如正常的一个请求,返回方式如下:

<code>return response($result, $code);  // 返回json
</code>
Copy after login
Copy after login

异常的请求,比如该路由没有被定义,该请求的方法没有被定义。如何也返回一个json对象呢,写在404.blade.php里肯定不合适,因为写进去的话会返回一个string

回复内容:

比如正常的一个请求,返回方式如下:

<code>return response($result, $code);  // 返回json
</code>
Copy after login
Copy after login

异常的请求,比如该路由没有被定义,该请求的方法没有被定义。如何也返回一个json对象呢,写在404.blade.php里肯定不合适,因为写进去的话会返回一个string

Middleware或者App\Exceptions\Handler里捕获
Symfony\Component\HttpKernel\Exception\NotFoundHttpException

如果是Middleware

<code>use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function handle($request, Closure $next) {
    try {
        return $next($request);
    } catch (NotFoundHttpException $e) {
        return response()->json(['msg'=>'NotFound']);
    }
}

</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template