I would like to customise the error messages displayed in my GraphQL queries for a coupon code in m2.
You should implement the \GraphQL\Error\ClientAware interface to handle errors in your module that are directly related to a GraphQL field having an anticipated exception. - Magento Documentation
{
class ApplyCouponToCart implements ResolverInterface
/**
* @var CouponManagementInterface
*/
private $couponManagement;
/**
* @param GetCartForUser $getCartForUser
* @param CouponManagementInterface $couponManagement
*/
public function __construct(
GetCartForUser $getCartForUser,
CouponManagementInterface $couponManagement
) {
$this->getCartForUser = $getCartForUser;
$this->couponManagement = $couponManagement;
}
/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (empty($args['input']['cart_id'])) {
throw new GraphQlInputException(__('Required parameter "cart_id" is missing'));
}
$maskedCartId = $args['input']['cart_id'];
if (empty($args['input']['coupon_code'])) {
throw new GraphQlInputException(__('Required parameter "coupon_code" is missing'));
}
$couponCode = $args['input']['coupon_code'];
$currentUserId = $context->getUserId();
$storeId = (int)$context->getExtensionAttributes()->getStore()->getId();
$cart = $this->getCartForUser->execute($maskedCartId, $currentUserId, $storeId);
$cartId = $cart->getId();
/* Check current cart does not have coupon code applied */
$appliedCouponCode = $this->couponManagement->get($cartId);
if (!empty($appliedCouponCode)) {
throw new GraphQlInputException(
__('A coupon is already applied to the cart. Please remove it to apply another')
);
}
I need an example of how I can catch this exceptions below, and customize just the text errors like
throw new GraphQlInputException(
__('I want to customise this text ')