Saloon
GithubOfficial BookSponsor
v3
v3
  • 🀠Saloon
  • Upgrade
    • πŸͺ„What's new in v3
    • 🌳Upgrading from v2
  • The Basics
    • ⬇️Installation
    • πŸ”ŒConnectors
    • βœ‰οΈRequests
    • πŸ”Authentication
    • 🎁Sending Body/Data
      • JSON Body
      • Multipart Form Body
      • XML Body
      • URL Encoded Body (Form)
      • String / Plain Text Body
      • Stream Body
    • πŸš€Sending Requests
    • πŸ“‘Responses
    • πŸ”₯Handling Failures
    • πŸ”ŽDebugging
    • βœ…Testing
  • Digging Deeper
    • πŸ›ΈData Transfer Objects
    • ✨Building SDKs
    • ☝️Solo Requests
    • 🎯Retrying Requests
    • ⏸️Delaying Requests
    • 🏎️Concurrency & Pools
    • πŸ”‘OAuth2
      • Authorization Code Grant
      • Client Credentials Grant
    • πŸ’«Middleware
    • ⛩️PSR Support
  • Installable Plugins
    • πŸ“šPagination
      • Paged Pagination
      • Limit/Offset Pagination
      • Cursor Pagination
      • Custom Pagination
    • β›΅Laravel Plugin
    • πŸ”Caching
    • β›”Rate Limit Handler
    • 🏭Auto SDK Generator
    • 🀠Lawman
    • πŸ‡XML Wrangler
    • πŸ—οΈBuilding Your Own Plugins
  • Conclusion
    • πŸ“˜Official Book!
    • πŸ“”How-to Guides
      • Improving Speed With Laravel
      • Per-request Authentication
    • πŸ“–Tutorials & Blog Posts
    • πŸŽ–οΈShowcase
    • πŸ’₯Known Issues
    • πŸ€—Credits
    • ❀️Support Saloon
Powered by GitBook
On this page
  • Always throw exceptions on failed requests
  • Using the throw method
  • Response Exceptions
  • Handling failures with promises
  • Customising when Saloon thinks a request has failed
  • Customising the request exception
Edit on GitHub
  1. The Basics

Handling Failures

Saloon has a powerful exception handler with many descriptive exceptions you can use in your application.

When you send a request, Saloon won't do anything if the request fails, but by default, it will use the status code to determine if a request is successful or not. The only exception to this is if Saloon cannot connect to an API, which will throw a FatalRequestException.

<?php

$forge = new ForgeConnector;
$response = $forge->send(new ErrorRequest);

$response->failed(); // true
$response->status(); // 500
$response->body(); // {"message": "Server Error"}

Always throw exceptions on failed requests

You may wish to throw an exception whenever a request fails (4xx or 5xx response). You can add the AlwaysThrowOnErrors trait on your connector, and then every request that fails will throw an exception.

<?php

use Saloon\Traits\Plugins\AlwaysThrowOnErrors;

class ForgeConnector extends Connector
{
    use AlwaysThrowOnErrors;
    
    // {...}
}

Using the throw method

On a per-response basis, you may use the throw method after sending your response. This method will throw an exception if the response has a "failed" HTTP status code like 4xx or 5xx.

<?php

$forge = new ForgeConnector;
$response = $forge->send(new ErrorRequest);

// throws InternalServerErrorException (extends ServerException)

$response->throw();

Response Exceptions

Saloon's default exception handler contains the following exceptions based on the status code and severity of the exception. These are thrown depending on the method you use below.

SaloonException
β”œβ”€β”€ FatalRequestException (Connection Errors)
└── RequestException (Request Errors)
    β”œβ”€β”€ ServerException (5xx)
    β”‚   β”œβ”€β”€ InternalServerErrorException (500)
    β”‚   β”œβ”€β”€ ServiceUnavailableException (503)
    β”‚   └── GatewayTimeoutException (504)
    └── ClientException (4xx)
        β”œβ”€β”€ UnauthorizedException (401)
        β”œβ”€β”€ PaymentRequiredException (402)
        β”œβ”€β”€ ForbiddenException (403)
        β”œβ”€β”€ NotFoundException (404)
        β”œβ”€β”€ MethodNotAllowedException (405)
        β”œβ”€β”€ RequestTimeOutException (408)
        β”œβ”€β”€ UnprocessableEntityException (422)
        └── TooManyRequestsException (429)

Handling failures with promises

When sending requests using sendAsync or using request pooling, you will receive a PromiseInterface instance. Since this class catches exceptions, Saloon will automatically pass the request exception in the otherwise block, and you do not have to use the throw method.

<?php

use Saloon\Http\Response;

$forge = new ForgeConnector('api-token');
$promise = $forge->sendAsync(new GetServersRequest);

$promise
    ->then(function (Response $response) {
        // Handle successful response
    })
    ->otherwise(function (RequestException $exception) {
        // Handle failed request
    });

Customising when Saloon thinks a request has failed

You may integrate with an API which returns a 200 response status but with an error message in the response body. To handle this, you can extend the hasRequestFailed method on your connector or request.

<?php

use Saloon\Http\Connector;
use Saloon\Http\Response;

class ForgeConnector extends Connector
{
    // {...}
    
    public function hasRequestFailed(Response $response): ?bool
    {
        return str_contains($response->body(), 'Server Error');
    }
}
<?php

use Saloon\Http\Request;
use Saloon\Http\Response;

class ErrorRequest extends Request
{
    // {...}
    
    public function hasRequestFailed(Response $response): ?bool
    {
        return str_contains($response->body(), 'Server Error');
    }
}

Customising the request exception

<?php

use Saloon\Http\Connector;
use Saloon\Http\Response;
use \Throwable;

class ForgeConnector extends Connector
{
    // {...}
    
    public function getRequestException(Response $response, ?Throwable $senderException): ?Throwable
    {
        return new CustomException('Oh yee-naw!', $response, $senderException);
    }
}
<?php

use Saloon\Http\Request;
use Saloon\Http\Response;
use \Throwable;

class ErrorRequest extends Request
{
    // {...}
    
    public function getRequestException(Response $response, ?Throwable $senderException): ?Throwable
    {
        return new CustomException('Oh yee-naw!', $response, $senderException);
    }
}

Priority is given to the request when you extend the getRequestException method on both your connector and request.

PreviousResponsesNextDebugging

Last updated 9 months ago

By default, Saloon will use the exceptions , but you may choose to return your own exception if a request has failed. Just extend the getRequestException method on either your connector or request. You will receive an instance of the response and a sender exception, which may be nullable.

πŸ”₯
listed above