Exceptions

Exceptions use to create an error and response to the client. we have a predefined structure that includes two base classes. first we should create a class and extend that from ValravnException class.

 1use Hans\Valravn\Exceptions\ValravnException;
 2use Illuminate\Database\Eloquent\Model;
 3use Symfony\Component\HttpFoundation\Response;
 4
 5class AppException extends ValravnException {
 6  public static function failedToDelete( Model $model ): ValravnException {
 7    return self::make(
 8      "Failed to delete [" . get_class( $model ) . "] $model->id",
 9      AppErrorCode::failedToDelete(),
10      Response::HTTP_INTERNAL_SERVER_ERROR
11    );
12  }
13}

Next, we need a class to manage our error codes.

1use Hans\Valravn\Exceptions\ErrorCode;
2
3class AppErrorCode extends ErrorCode {
4  protected static string $prefix = 'AppECx';
5
6  protected int $failedToDelete = 1;
7
8}

The related property can be defined in other ways. for example, you can define the property like $FAILED_TO_DELETE or just define a method like below

 1use Hans\Valravn\Exceptions\ErrorCode;
 2
 3class ValravnErrorCode extends ErrorCode {
 4  protected static string $prefix = 'ValravnECx';
 5
 6  public static function failedToDelete(): string {
 7      return self::$prefix . "1";
 8  }
 9
10}
If you are defining an ErrorCode as a method, don't forget to prefix the number.