Laravel 404和500的API和网站中的不同响应(JSON和网页)?

Pra*_*rve 5 laravel laravel-5.4

我想展示API和网站的不同响应.在api响应中,我想用404和500显示json响应,主要用于路由的异常类型.

如果用户尝试请求未找到的路由和路由,我想在json响应中显示API的响应和网站的网页.

我知道并尝试编码 app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('404', [], 404);
    }
    return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)

https://laravel.com/docs/5.4/errors#http-exceptions

但是失败的任何人都可以帮助我如何为错误页面设置不同的响应.

mrh*_*rhn 9

期待JSON是关于标题,我不喜欢API错误的解决方案,说实话,你可以通过浏览器访问它.我的解决方案大多数时候都是通过URL路由进行过滤,因为它最常见的开头"api/...",可以这样做$request->is('api/*').

如果您有/ api路由,那么这将起作用,否则更改确定它是否是API路由的逻辑.

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        if ($request->is('api/*')) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('404', [], 404);
    }
    return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,还添加```使用Symfony\Component\HttpKernel\Exception\NotFoundHttpException;```Thankyou (3认同)