Laravel API, how to properly handle errors

后端 未结 6 1028
后悔当初
后悔当初 2021-01-30 15:16

Anyone know what is the best way to handle errors in Laravel, there is any rules or something to follow ?

Currently i\'m doing this :

public function st         


        
6条回答
  •  感动是毒
    2021-01-30 15:33

    Laravel is already able to manage json responses by default.

    Withouth customizing the render method in app\Handler.php you can simply throw a Symfony\Component\HttpKernel\Exception\HttpException, the default handler will recognize if the request header contains Accept: application/json and will print a json error message accordingly.

    If debug mode is enabled it will output the stacktrace in json format too.

    Here is a quick example:

    getMessage());
            }
    
            return $myObject;
        }
    }
    

    Here is laravel response with debug off

    {
        "message": "My custom error"
    }
    

    And here is the response with debug on

    {
        "message": "My custom error",
        "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
        "file": "D:\\www\\myproject\\app\\Http\\Controllers\\ApiController.php",
        "line": 24,
        "trace": [
            {
                "file": "D:\\www\\myproject\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\ControllerDispatcher.php",
                "line": 48,
                "function": "myAction",
                "class": "App\\Http\\Controllers\\ApiController",
                "type": "->"
            },
            {
                "file": "D:\\www\\myproject\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Route.php",
                "line": 212,
                "function": "dispatch",
                "class": "Illuminate\\Routing\\ControllerDispatcher",
                "type": "->"
            },
    
            ...
        ]
    }
    

    Using HttpException the call will return the http status code of your choice (in this case internal server error 500)

提交回复
热议问题