๐Ÿšช
Saloon
๐Ÿง‘โ€๐Ÿ’ป View Code On Github๐Ÿค  Version 3 is out!๐Ÿ’– Support The Project
v1 (Security Fixes Only)
v1 (Security Fixes Only)
  • ๐ŸšชSaloon
  • ๐Ÿš€Getting Started
    • Installation
  • ๐Ÿค The Basics
    • Connectors
    • Requests
    • Attaching Data
    • Query Parameters
    • Sending Requests
    • Responses
      • Data Transfer Objects
    • Building SDKs
  • ๐Ÿ‘Next Steps
    • Authentication
    • Plugins
    • Caching
    • Mocking Responses
      • Non-Laravel / PHP
      • Laravel
      • Recording Requests
  • ๐ŸงชAdvanced
    • OAuth2 Authentication
    • Response Interceptors
    • Handlers / Middleware
  • โญFinish
    • Showcase
    • Tutorials
    • View Code On GitHub
    • Update Docs
    • About Me
    • Donate
Powered by GitBook
On this page
  • Example Response Interceptor
  • Macroable
  • Custom Responses
Edit on GitHub
  1. ๐ŸงชAdvanced

Response Interceptors

Last updated 2 years ago

Saloon already allows you to add functionality to your requests in the form of plugins, but if you would like to intercept the response before it is passed back to you, you can add a response interceptor. These can be added into Saloon plugins, or they can be added to the boot method on the Connector/Request.

Example Response Interceptor

This response interceptor will tell all responses to "throw" an exception if it fails. Response interceptors provide you with the SaloonRequest and the request and the SaloonResponse.

<?php

class CreateForgeServerRequest extends SaloonRequest
{
    //...

    public function boot(SaloonRequest $request): void
    {
        $this->addResponseInterceptor(function (SaloonRequest $request, SaloonResponse $response) {
            $response->throw();
    
            return $response;
        });
    }
}

This interceptor example is a plugin pre-built into Saloon, have a look at the

Macroable

Saloon Responses are also "Macroable" which means you can add your own methods to them to use later.

<?php

class CreateForgeServerRequest extends SaloonRequest
{
    //...

    public function boot(SaloonRequest $request): void
    {
        $this->addResponseInterceptor(function (SaloonRequest $request, SaloonResponse $response) {
            $response::macro('hello', function ($name) {
                return 'Hello ' . $name;
            });
    
            return $response;
        });
    }
}

After we have defined the macro, we can use it like this.

$response->hello('Sam'); // Returns "Hello Sam" 

Custom Responses

If you are looking to overwrite Saloon's response methods or if you would like to add lots of your own methods, consider creating a custom response. .

Read more
AlwaysThrowsOnErrors plugin