PHP Try and Catch for SQL Insert

前端 未结 9 981
南方客
南方客 2020-12-15 18:05

I have a page on my website (high traffic) that does an insert on every page load.

I am curious of the fastest and safest way to (catch an error) and continue if the

9条回答
  •  伪装坚强ぢ
    2020-12-15 18:16

    $new_user = new User($user);
    $mapper = $this->spot->mapper("App\User");
    
    try{
        $id = $mapper->save($new_user);     
    }catch(Exception $exception){
    
        $data["error"] = true;
        $data["message"] = "Error while insertion. Erron in the query";
        $data["data"] = $exception->getMessage();
    
        return $response->withStatus(409)
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));        
    }
    

    if error occurs, you will get something like this->

    {
        "error": true,
        "message": "Error while insertion. Erron in the query",
        "data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for integer: \"default\"" }
    

    with status code:409.

提交回复
热议问题