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

时间:2015-02-19 23:50:19

标签: json laravel laravel-5

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

当laravel从数据库中找到记录时,它返回正确的json数据。是的! 如果laravel无法搜索任何记录,它就不会提供json数据! laravel只是重新编辑了显示"哎呀,看起来出了问题的页面。"并给出了额外的信息," 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);

            }
   }

1 个答案:

答案 0 :(得分:1)

我解决了问题。首先,我改变了findOrFail方法来查找方法。其次,我实现了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);
    }