当 Laravel 5 捕获异常时,如何 return json 数据?

How can I return json data when Laravel 5 catch exception?

如何在laravel捕获异常时returnjson数据? 当数据库中不存在数据时,我想 return Json 数据。

当 laravel 从数据库中找到记录时,它 return 是正确的 json data.Yeah! 如果 laravel 没有搜索到任何记录,它不会给出 json 数据! laravel 刚刚重定向了显示 "Whoops, looks like something went wrong." 的页面并提供了额外的信息,"ModelNotFoundException".

下面的代码是我试过的。

    public function show($id)
    {
            try {
                    $statusCode = 200;
                    $response = [
                            'todo' => []
                    ];

                    $todo = Todo::findOrFail($id);

                    $response['todo']= [
                            'id'       =>       $todo->id,
                            'title'    =>       $todo->title,
                            'body'     =>       $todo->body,
                    ]; 

            } catch(Exception $e) {
                    // I think laravel doesn't go through following exception
                    $statusCode = 404;   
                    $response = [
                            "error" => "You do not have that record"
                    ];

            } finally {
                    return response($response, $statusCode);

            }
   }

我解决了问题。首先,我将findOrFail 方法更改为find 方法。其次,我意识到 Exception 并且 Illuminate\Database\Eloquent\ModelNotFoundException $e 无法捕捉到任何东西。所以我改成if条件。然后就可以了。

    public function show($id)
    {        
            $statusCode = 200;
            $response = [
                    'todo' => []
            ];

            $todo = Todo::find($id);

            if ( is_null($todo) ) {
                    $statusCode = 404;
                    $response = [
                            "error" => "The record doesn't exist"
                    ];

            } else {
                    $response['todo']= [
                            'id'       =>       $todo->id,
                            'title'    =>       $todo->title,
                            'body'     =>       $todo->body,
                    ]; 

            }

            return response($response, $statusCode);
    }