1

I'm looking for some way to try catch in Magento with AJAX and then alert the error message out.
I'm following some solution but doesn't work.
Ok so here is what I've done til now :

C:\xampp\htdocs\magento\app\code\Aht\BannerSlider\view\frontend\templates\index.phtml

<?php
$check = $this->helper('Aht\BannerSlider\Helper\Check');
if ($check->checkAllowedPage() != false):
 $full_route = $check->checkAllowedPage();
 ?>
 <div id="banner_slide_after_ajax_loaded"></div>
 <script>
 require([
 'jquery'
 ], function ($) {
 $(document).ready(function () {
 $.ajax({
 url: 'http://localhost/magento/banner/slide/image',
 method: 'GET',
 dataType: 'html', // muốn render html thì cần phải có dòng này.
 data: {
 width: screen.width,
 height: screen.height,
 full_route: '<?php echo $full_route; ?>'
 },
 success: function (response) {
 response = $.parseJSON(response);
 // if (response.errorMessage) {
 // alert(response.errorMessage);
 // } else {
 $('#banner_slide_after_ajax_loaded').append(response.html);
 // }
 },
 error: function(xhr, textStatus, error){
 console.log(xhr.statusText);
 console.log(textStatus);
 console.log(error);
 }
 });
 });
 });
 </script>
<?php endif; ?>


Should I've to set status code in this file? And how to return response error message?

C:\xampp\htdocs\magento\app\code\Aht\BannerSlider\Controller\Slide\Image.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 17/07/2018
 * Time: 4:35 CH
 */
namespace Aht\BannerSlider\Controller\Slide;
class Image extends \Magento\Framework\App\Action\Action
{
 protected $_pageFactory;
 protected $coreRegistry;
 protected $resultJsonFactory;
 public function __construct(
 \Magento\Framework\App\Action\Context $context,
 \Magento\Framework\Registry $coreRegistry,
 \Magento\Framework\View\Result\PageFactory $pageFactory,
 \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
 )
 {
 $this->coreRegistry = $coreRegistry;
 $this->_pageFactory = $pageFactory;
 $this->resultJsonFactory = $resultJsonFactory;
 return parent::__construct($context);
 }
 public function execute()
 {
// gửi width,height và full_route qua block bằng register
 $html = '';
 $errorMessage = false;
 try{
 $width = $this->getRequest()->getParam('width');
 $height = $this->getRequest()->getParam('height');
 $full_route = $this->getRequest()->getParam('full_route');
 $resolution_screen = array($width,$height);
 $this->coreRegistry->register('resolution_screen', $resolution_screen);
 $this->coreRegistry->register('full_route', $full_route);
 $resultPage = $this->_pageFactory->create();
 $html = $resultPage->getLayout()
 ->createBlock('Aht\BannerSlider\Block\Frontend\Slide')
 ->setTemplate('Aht_BannerSlider::slide.phtml')
 ->toHtml();
 $resultJson = $this->resultJsonFactory->create();
 } catch (\Exception $e){
 $errorMessage = 'There is something wrong!';
 $this->messageManager->addErrorMessage($errorMessage);
 $respone = $resultJson->setData(['errorMessage' => $errorMessage]);
 return $respone;
 }
 $respone = $resultJson->setData(['html' => $html, 'errorMessage' => $errorMessage]);
 return $respone;
 }
}


EDIT 1:

So i've followed @Kumar M solution, and this is the result:

public function execute()
 {
// gửi width,height và full_route qua block bằng register
 $html = '';
 $errorMessage = false;
 $resultJson = $this->resultJsonFactory->create();
 try{
 $width = $this->getRequest()->getParam('width');
 $height = $this->getRequest()->getParam('height');
 $full_route = $this->getRequest()->getParam('full_route');
 $resolution_screen = array($width,$height);
 $this->coreRegistry->register('resolution_screen', $resolution_screen);
 $this->coreRegistry->register('full_route', $full_route);
 $resultPage = $this->_pageFactory->create();
 $html = $resultPage->getLayout()
 ->createBlock('Aht\BannerSlider\Block\Frontend\Slide')
 ->setTemplate('Aht_BannerSlider::slide.phtml')
 ->toHtml();
 } catch (\Exception $e){
 $errorMessage = 'There is something wrong!';
// $this->messageManager->addErrorMessage($errorMessage);
 $respone = $resultJson->setData(['errorMessage' => $errorMessage]);
 return $respone;
 }
 $respone = $resultJson->setData(['html' => $html, 'errorMessage' => $errorMessage]);
 return $respone;
 }

So now i wanna know how to test this, i mean how to make an error so it can run to catch()? Thanks :)

asked Aug 17, 2018 at 4:34

1 Answer 1

2

So as per you script, do the following:

  1. You have initialised resultJson object inside try at very last line in try. So when catch will be calling resultJson will not have that class object. So put this line before try:

    $resultJson = $this->resultJsonFactory->create();

  2. As I can see in your js you must send html and errorMessage parameters always even its in catch, as you have used .html from response object in Ajax success.

And it's not necessary to call messageManager while you are performing from Ajax. You can simply add that error message into Ajax response.

answered Aug 17, 2018 at 5:15
4
  • Thanks for useful answer :) I'll update the code and feed back to you later :) Commented Aug 17, 2018 at 8:07
  • U got +1 from me :) Commented Aug 17, 2018 at 8:07
  • Hi, sorry for late reply, i've updated after you and edit my post, so please check :) Thanks. By the way, i dont know how to test this, i mean how to make it error so it can run to catch() ? Commented Aug 20, 2018 at 1:20
  • Use this in try:. throw new \Exception("hi this is error"); Commented Aug 20, 2018 at 4:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.