Error Handling
Sajya tries to fully comply with the standards and expectations that apply to Laravel. For example, with the debug
option enabled in the config/app.php
configuration file, the response error information will contain much more information.
Throw Exceptions
During operation, you can throw exceptions that will be converted into a valid JSON-RPC response without your intervention. For example:
declare(strict_types=1);
namespace App\Http\Procedures;
use Exception;
use Sajya\Server\Procedure;
class TennisProcedure extends Procedure
{
public static string $name = 'tennis';
public function ping()
{
throw new Exception('Division by zero.', -100);
}
}
Will lead to the following response:
{
"id": "1",
"error": {
"code": -100,
"message": "Division by zero."
....
},
"jsonrpc": "2.0"
}
In order not to repeat, you can make your exception class for this, use inheritance from Sajya\Server\Exceptions\RpcException
. To do this, create a new Exception class with the Artisan
command:
php artisan make:exception DivisionByZero
A new file will be created in the app/Exceptions
directory. Let's change the inheritance to support RPC and define the description and error code:
<?php
declare(strict_types=1);
namespace App\Exceptions;
use Sajya\Server\Exceptions\RpcException;
class DivisionByZero extends RpcException
{
/**
* A String providing a short description of the error.
* The message SHOULD be limited to a concise single sentence.
*
* @return string
*/
protected function getDefaultMessage(): string
{
return 'Division by zero.';
}
/**
* A Number that indicates the error type that occurred.
* This MUST be an integer.
*
* @return int
*/
protected function getDefaultCode(): int
{
return -100;
}
}
We can then throw an exception at runtime and the client will get the correct error code and description:
declare(strict_types=1);
namespace App\Http\Procedures;
use App\Exceptions\DivisionByZero;
use Sajya\Server\Procedure;
class TennisProcedure extends Procedure
{
public static string $name = 'tennis';
public function ping()
{
throw new DivisionByZero();
}
}
Reporting Exceptions
Well as in HTTP, where certain types of errors are ignored, such as 404 "not found" errors or 419 responses generated by invalid CSRF tokens. JSON-RPC has the following ignored exceptions that will not be logged:
- Invalid params (-32602)
- Invalid request (-32600)
- Method not found (-32601)
- Parse error (-32700)