Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Andreas94's avatar

Receive status response from API post

I have a post api that I can't get the error message, because he executes exemple the post and laravel sends me to the Stack page with the error:

Client error: `POST https://****/api/core/members?key=****` resulted in a `403 Forbidden` response: { "errorCode": "1C292\/4", "errorMessage": "USERNAME_EXISTS" }

I would need that if he finds an error, like in this case the "errorCode": "1C292\/4", he doesn't execute the code but puts an alert on my page, how to do that?

  public function postRegister(Request $request) {
      $endpoint = 'https://***/api/core/members?key=***';
      $options = [
        'form_params' => [
          'name' => $request->name,
          'email' => $request->email,
        ]
      ];
      $client = new Client();
      $response =  $client->post($endpoint, $options);
      echo $response->getStatusCode();
  }

He immediately executes the string $response = $client->post($endpoint, $options) and it gives me error on the screen, how can I parse the errorcode before the post request?

0 likes
1 reply
Andreas94's avatar
Andreas94
OP
Best Answer
Level 2

Solved by using the try and catch

try {
api
}catch (BadResponseException $ex) {
      $response = json_decode($ex->getResponse()->getBody()->getContents(), true);
      $data = $response['errorCode'];
      if($data == "***") {
        echo "test";
      } elseif($data == "***") {
        echo " test1";
      } else {
        echo "other error ".$data;
      }
    }

Please or to participate in this conversation.