Laravel 5一般错误为json

And*_*res 21 laravel-5

我只是移动到laravel 5并且我在HTML页面中从laravel接收错误.像这样的东西:

Sorry, the page you are looking for could not be found.

1/1
NotFoundHttpException in Application.php line 756:
Persona no existe
in Application.php line 756
at Application->abort('404', 'Person doesnt exists', array()) in helpers.php line 
Run Code Online (Sandbox Code Playgroud)

当我使用laravel 4时,一切正常,错误是json格式,这样我就可以解析错误消息并向用户显示消息.json错误的一个例子:

{"error":{
"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"message":"Person doesnt exist",
"file":"C:\\xampp\\htdocs\\backend1\\bootstrap\\compiled.php",
"line":768}}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在laravel 5中实现这一目标.

抱歉我的英语不好,非常感谢.

小智 25

我之前来到这里寻找如何在Laravel的任何地方抛出json异常,答案让我在正确的路径上.对于那些发现这种搜索类似解决方案的人来说,这是我在应用程序范围内实现的方式:

将此代码添加到render方法中app/Exceptions/Handler.php

if ($request->ajax() || $request->wantsJson()) {
    return new JsonResponse($e->getMessage(), 422);
}
Run Code Online (Sandbox Code Playgroud)

将此添加到方法来处理对象:

if ($request->ajax() || $request->wantsJson()) {

    $message = $e->getMessage();
    if (is_object($message)) { $message = $message->toArray(); }

    return new JsonResponse($message, 422);
}
Run Code Online (Sandbox Code Playgroud)

然后在任何地方使用这个通用代码:

throw new \Exception("Custom error message", 422);
Run Code Online (Sandbox Code Playgroud)

并且它会将ajax请求之后抛出的所有错误转换为准备好以任何你想要的方式使用的Json异常:-)

  • 如果是Laravel 5.1,则返回应该是"return response() - > json($ e-> getMessage(),422);" (10认同)

Ign*_*ual 12

Laravel 5.1

保持我的HTTP状态代码出现意外异常,例如404,500 403 ...

这是我使用的(app/Exceptions/Handler.php):

 public function render($request, Exception $e)
{
    $error = $this->convertExceptionToResponse($e);
    $response = [];
    if($error->getStatusCode() == 500) {
        $response['error'] = $e->getMessage();
        if(Config::get('app.debug')) {
            $response['trace'] = $e->getTraceAsString();
            $response['code'] = $e->getCode();
        }
    }
    return response()->json($response, $error->getStatusCode());
}
Run Code Online (Sandbox Code Playgroud)


Zan*_*per 6

Laravel 5提供了一个异常处理程序app/Exceptions/Handler.php.该render方法可用于以不同方式呈现特定异常,即

public function render($request, Exception $e)
{
    if ($e instanceof API\APIError)
        return \Response::json(['code' => '...', 'msg' => '...']);
    return parent::render($request, $e);
}
Run Code Online (Sandbox Code Playgroud)

就个人而言,App\Exceptions\API\APIError当我想要返回API错误时,我会将其作为一般异常使用.相反,您可以检查请求是否是AJAX(if ($request->ajax())),但我认为显式设置API异常似乎更清晰,因为您可以扩展APIError类并添加所需的任何功能.


Bil*_*kin 5

编辑:Laravel 5.6 可以很好地处理它而无需任何更改,只需确保您将Accept标头作为application/json.


如果你想保留状态代码(这对前端理解错误类型很有用)我建议在你的 app/Exceptions/Handler.php 中使用它:

public function render($request, Exception $exception)
{
    if ($request->ajax() || $request->wantsJson()) {

        // this part is from render function in Illuminate\Foundation\Exceptions\Handler.php
        // works well for json
        $exception = $this->prepareException($exception);

        if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
            return $exception->getResponse();
        } elseif ($exception instanceof \Illuminate\Auth\AuthenticationException) {
            return $this->unauthenticated($request, $exception);
        } elseif ($exception instanceof \Illuminate\Validation\ValidationException) {
            return $this->convertValidationExceptionToResponse($exception, $request);
        }

        // we prepare custom response for other situation such as modelnotfound
        $response = [];
        $response['error'] = $exception->getMessage();

        if(config('app.debug')) {
            $response['trace'] = $exception->getTrace();
            $response['code'] = $exception->getCode();
        }

        // we look for assigned status code if there isn't we assign 500
        $statusCode = method_exists($exception, 'getStatusCode') 
                        ? $exception->getStatusCode()
                        : 500;

        return response()->json($response, $statusCode);
    }

    return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)