Exception handling

Usually we put the exception class in app/Exception , and the exception class handler places the app/Exception/Handler exception into two parts. Custom Exception exception class, exception handling class ExceptionHandler

Defining exception classes

Define different exception classes in different application scenarios, such as classes that require a controller to throw exceptions.


 namespace App\Exception;
class ApiException extends \Exception


Defining exception handling classes

 namespace App\Exception\Handler;
use App\Exception\ApiException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
 * @ExceptionHandler(ApiException::class)
class ApiExceptionHandler extends AbstractHttpErrorHandler
     * @param \Throwable $e
     * @param Response $response
     * @return Response
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
    public function handle(\Throwable $e, Response $response): Response
        $data = ['code'=>-1,'msg'=>$e->getMessage()];
        return $response->withData($data);



Exception handler, specifying that this handler should handle exceptions. When the program throws an exception in the ExceptionHandler annotation, it will automatically execute the handle method.

  • Specify exception: parameter can be a string or an array

Handling an exception


Handling multiple exceptions