Is there a standard way in Magento 2 to programmatically trigger an HTTP error state and have the system just deal with it? i.e. is there a standard exception we can throw or global method we can call when, in our code, something unexpected happens and we just want to send the user to an error page?

Or is the only way to deal with this to create your own error state, and then ensure your controller's execute method returns an appropriate error code?


You can always return \Magento\Framework\Controller\Result\Raw with custom status header.

Also you can send 404 by throwing \Magento\Framework\Exception\NotFoundException. It will be processed in lib/internal/Magento/Framework/App/FrontController.php:61 to 'noroute' path, which will resolve to \Magento\Cms\Controller\Noroute\Index (or more specific if defined) that will set 404 header.

Most non-init errors will resolve to 503 Response code. See \Magento\Framework\App\Http::catchException for details.


As suggested by @Anton Kril, this worked for me.

namespace Company\ModuleName\Controller\Index;

use Magento\Framework\App\Action\Context;
use \Magento\Framework\Exception\NotFoundException;

class Index extends \Magento\Framework\App\Action\Action {
    public function execute() {
        throw new NotFoundException(__('Some Exception message.'));                 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.