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

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

WBOY
WBOYOriginal
2016-06-06 20:31:561059browse

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

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

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

回复内容:

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

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

异常的请求,比如该路由没有被定义,该请求的方法没有被定义。如何也返回一个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>
Statement:
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