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 :)
1 Answer 1
So as per you script, do the following:
You have initialised
resultJsonobject insidetryat verylast lineintry. So whencatchwill be callingresultJsonwill not have thatclass object. So put this line before try:$resultJson = $this->resultJsonFactory->create();
As I can see in your
jsyou must sendhtmlanderrorMessageparameters always even its incatch, as you have used.htmlfromresponseobject inAjax 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.
-
Thanks for useful answer :) I'll update the code and feed back to you later :)fudu– fudu2018年08月17日 08:07:39 +00:00Commented 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() ?fudu– fudu2018年08月20日 01:20:35 +00:00Commented Aug 20, 2018 at 1:20
-
Use this in try:. throw new \Exception("hi this is error");Kumar M– Kumar M2018年08月20日 04:01:32 +00:00Commented Aug 20, 2018 at 4:01